根据字段数组中的值查找Doctrine2


Doctrine2 find by value in field array

我想知道是否有一种方法来搜索文档字段,看起来像:

/**
 * @var array
 *
 * @ORM'Column(name="tags", type="array", nullable=true)
 */
private $tags;

在数据库中看起来像PHP数组解释:

a:3:{i:0;s:6:"tagOne";i:1;s:6:"tagTwo";i:2;s:8:"tagThree";}

现在我试着通过一个标签来搜索这个实体

public function findByTag($tag) {
    $qb = $this->em->createQueryBuilder();
    $qb->select('u')
        ->from("myBundle:Entity", 'u')
        ->where('u.tags LIKE :tag')
        ->setParameter('tag', $tag );
    $result=$qb->getQuery()->getResult();
    return $result;
}

总是返回array[0]就别明白了

我可以改变它们被保存的方式如有任何帮助,请提前感谢

您需要为%定义一个literal标记,在您想要搜索的值之前和/或之后;在这种情况下,你甚至不需要在你的短语之前和之后使用单引号:

$qb = $this->em->createQueryBuilder();
$qb->select('u')
    ->from("myBundle:Entity", 'u')
    ->where($qb->expr()->like('u.tags', $qb->expr()->literal("%$tag%")))
$result=$qb->getQuery()->getResult();
return $result;

您可以遵循所有Doctrine expr class的列表

我在几个月前实现了这一点—您错过了%通配符。您可以执行以下操作:

$qb->select('u')
    ->from("myBundle:Entity", 'u')
    ->where('u.tags LIKE :tag')
    ->setParameter('tag', '%"' . $tag . '"%' );

显然,关键部分是放置%通配符,但是您还需要放置"(双引号)以防止选择部分匹配(如果必要的话)。把这些去掉,包括部分,但因为你正在搜索标签,我认为这不是情况。

根据前面的回答和我在评论中表达的一个想法,我决定使用这个通用静态函数来完成这项工作:

/**
     * @param EntityManagerInterface $entityManager
     * @param string                 $entity
     * @param string                 $arrayField
     * @param string                 $string
     *
     * @return array
     */
    public static function findByStringInArrayField(
        EntityManagerInterface $entityManager,
        string $entity,
        string $arrayField,
        string $string
    ): array {
        $serializedString = serialize($string);
        $columnName       = $entityManager->getClassMetadata($entity)->getColumnName($arrayField);
        $qb               = $entityManager->createQueryBuilder();
        return $qb->select('u')
                  ->from($entity, 'u')
                  ->where(
                      $qb->expr()
                         ->like(
                             "u.$columnName",
                             $qb->expr()->literal("%$serializedString%")
                         )
                  )
                  ->getQuery()
                  ->getResult();
    }

…,并将从ServiceEntityRepository中调用它,像这样:

$entities = self::findByStringInArrayField($this->getEntityManager(), MyEntity::class, 'tags', $tag);