Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 find by value in field array

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

/**
 * @var array
 *
 * @ORM\Column(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

like image 563
john Smith Avatar asked Jan 29 '26 23:01

john Smith


2 Answers

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

like image 56
Javad Avatar answered Jan 31 '26 18:01

Javad


I achieved this few months ago - you're missing the % wildcards. You could do the following:

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

The critical part, obviously, is placing % wildcards, but you would also need to put " (double quotes) for preventing the selection of partial matches (if necessary). Leave those out to include partials as well but since you're searching for the tags I don't think that's the case.

Hope this helps...

like image 24
Jovan Perovic Avatar answered Jan 31 '26 18:01

Jovan Perovic