我正在使用symfony3实现在条令中具有多对多关系的类别过滤器。我有一个实体Business
和Category
与多对多关联。具有多对多关系的新表如下所示
business_id category_id
1 1
1 2
2 1
2 2
3 1
现在我想得到所有有
category_id=1 and category_id=2
的业务。它应该选择business id
1,2
。我的Sql查询:-
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或条令查询都可以工作。
我非常感谢你的帮助。
最佳答案
为了得到两个类别中存在的业务,您可以编写如下的查询生成器,假设您的实体被映射成适当的多对多关系。
$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