寻求实现同时匹配多个Taxon ID的Doctrine查询函数
解决Doctrine中查询同时关联多个Taxon的产品问题
我明白你要解决的问题——找出同时关联了taxon ID 47和101的所有产品ID,IN()确实满足不了这个需求,因为它只会返回匹配任一条件的结果。下面给你两种用Doctrine实现目标的方案:
方案1:自连接(对应你原有的SQL逻辑)
这种方式和你写的原生SQL逻辑完全一致,通过自连接product_taxon表,确保同一个产品同时存在两条分别关联47和101的记录。
使用QueryBuilder实现
$entityManager = $this->getDoctrine()->getManager(); $qb = $entityManager->createQueryBuilder(); $results = $qb->select('pt.product_id') ->from('App\Entity\ProductTaxon', 'pt') // 替换成你的实体类路径 ->innerJoin( 'App\Entity\ProductTaxon', 'pt2', 'WITH', 'pt.product_id = pt2.product_id AND pt2.taxon_id = :targetTaxon2' ) ->where('pt.taxon_id = :targetTaxon1') ->setParameter('targetTaxon1', 47) ->setParameter('targetTaxon2', 101) ->getQuery() ->getResult();
使用DQL实现
SELECT pt.product_id FROM App\Entity\ProductTaxon pt JOIN App\Entity\ProductTaxon pt2 WITH pt.product_id = pt2.product_id AND pt2.taxon_id = 101 WHERE pt.taxon_id = 47
方案2:分组统计(更灵活的多Taxon匹配)
如果以后需要匹配更多Taxon(比如3个甚至更多),这种分组+HAVING的方式扩展性更强,通过统计每个产品关联的目标Taxon数量来筛选。
使用QueryBuilder实现
$entityManager = $this->getDoctrine()->getManager(); $qb = $entityManager->createQueryBuilder(); $targetTaxons = [47, 101]; $results = $qb->select('pt.product_id') ->from('App\Entity\ProductTaxon', 'pt') ->where('pt.taxon_id IN (:targetTaxons)') ->setParameter('targetTaxons', $targetTaxons) ->groupBy('pt.product_id') ->having('COUNT(DISTINCT pt.taxon_id) = :taxonCount') ->setParameter('taxonCount', count($targetTaxons)) ->getQuery() ->getResult();
使用DQL实现
SELECT pt.product_id FROM App\Entity\ProductTaxon pt WHERE pt.taxon_id IN (47, 101) GROUP BY pt.product_id HAVING COUNT(DISTINCT pt.taxon_id) = 2
为什么IN()不行?
IN()的逻辑是匹配任一给定值,只要产品关联了47或者101中的任意一个,就会被返回。而我们需要的是产品同时关联两个Taxon,所以必须通过自连接确认两条记录存在,或者通过分组统计确保所有目标Taxon都被关联。
内容的提问来源于stack exchange,提问作者Dmitrijs Čornobiļs
相关产品推荐
相关产品推荐

