Sql/Doctrine 查询查找具有多对多关联的多个条件的数据

2023-12-07

我正在使用 symfony3 实现具有多对多关系的类别过滤器。我有一个实体Business and Category具有多对多关联。具有多对多关系的新表如下所示

business_id   category_id
1              1
1              2
2              1
2              2
3              1

现在我想要获得所有拥有的企业category_id=1 and category_id=2.

它应该选择企业 ID1,2.

Mysql 查询:-

SELECT * FROM business
LEFT JOIN business_category ON business_category.business_id=business.id
WHERE business_category.category_id = 1 AND business_category.category_id = 2

任何 SQL 或 Doctrine 查询都可以工作。

我非常感谢您的帮助。


要获取两个类别中都存在的业务,您可以按如下方式编写查询生成器,我假设您的实体已映射为正确的多对多关系

$repo = $this->getDoctrine()->getRepository('YourBundle:Business');

$repo = $this->createQueryBuilder('b')
    ->addSelect('COUNT(DISTINCT  c.id) AS total_categories')
    ->innerJoin('b.categories', 'c');

$categoryIds = array(1,2);

$repo->add('where', $qb->expr()->in('c', $categoryIds))
    ->groupBy('b.id')
    ->having('total_categories = '.count($categoryIds))
    ->getQuery()
    ->getResult();

参考一下另一个答案here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Sql/Doctrine 查询查找具有多对多关联的多个条件的数据 的相关文章

随机推荐