Doctrine2 find by value in field array

Tags: , , , ,



i wonder if there is a way to search for a document field looking like :

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

which in database looks like php array interpretation :

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

now i try to search the entity by a tag tryed

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;
}

which always returns array[0] just dont get it

i am able to change the way how they are saved for any help, thanks in advance

Answer

You need to define a literal tag for % before and/or after the value you want to search; in this case you won’t even need to have single quotation before and after your phrase:

$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;

You can follow a list of all Doctrine expr class



Source: stackoverflow