我正在尝试查询包含所有已定义相关记录的特定记录。
这个例子不言而喻:
$qb->select('p')
->from('CommonBundle:MyTerm', 'p')
->leftJoin('p.propertyTypes','pt')
->where('pt.id IN (:ids)')
->setParameter('ids', array(1, 2, 3));
这将返回与 pt.id 1、2 或 3 关联的所有记录。
但我想要具有关联 ID 1、2 和 3 的记录, 知道我该怎么做吗?或者我应该使用“group by”和计数?
最佳答案
我通过连接同一张表两次解决了这个问题,如下所示:
$qb->select('COUNT(DISTINCT ptnot.id) AS ptnotcount, p')
->from('CommonBundle:MyTerm', 'p')
->leftJoin('p.propertyTypes','pt')
->leftJoin('p.propertyTypes','ptnot')
->where('(pt.id in (:ids) OR ptnot.id in (:notids))')
->setParameter('ids', array(1, 2, 3))
->setParameter('notids', array(4, 5, 6))
->groupBy('p.id')
->having('ptnotcount = 3'); // Size of the 'ids' array
我基本上是在查询应该存在的所有内容,以及不应该存在的所有内容。
然后我查看所有不同 propertyTypes
id 的计数是否与我们想要的相匹配。
关于mysql - 查询具有所有 ManyToMany id 的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34198193/