Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search in many-to-many relationship with Doctrine2

This is probably an easy one but I can't figure it out nor find an answer.

I have a simple Article and ArticleTag Entities with many to many relationship. How can I get all articles with a certain tag (or tags)?

My following tries:

$qb = $repository->createQueryBuilder('a')
    // ...
    ->andWhere('a.tags = :tag')
    ->setParameter('tag', 'mytag')
    // ...

or

    ->andWhere(':tag in a.tags')
    ->setParameter('tag', 'mytag')

...didn't work. Thanks!

like image 560
Czechnology Avatar asked Sep 23 '11 09:09

Czechnology


2 Answers

And the winner is ... drumroll, please ...

$qb = $repository->createQueryBuilder('a')
    // ...
    ->andWhere(':tag MEMBER OF a.tags');
    ->setParameter('tag', $tag);
    // ...

Thanks to everyone who has taken the time to read and think about my question!

like image 93
Czechnology Avatar answered Nov 14 '22 13:11

Czechnology


I think you can adаpt this example (from documentation):

$query = $em->createQuery('SELECT u.id FROM CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM CmsPhonenumber p WHERE p.user = u.id)');
like image 1
dmirkitanov Avatar answered Nov 14 '22 12:11

dmirkitanov