搜索与Doctrine2的多对多关系

时间:2021-09-12 20:49:34

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)?

我有一个简单的文章和ArticleTag实体有很多关系。如何获得带有特定标签(或标签)的所有文章?

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!

......没用谢谢!

2 个解决方案

#1


41  

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!

感谢所有花时间阅读和思考我的问题的人!

#2


1  

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)');

#1


41  

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!

感谢所有花时间阅读和思考我的问题的人!

#2


1  

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)');