在Doctrine中如何通过子查询实现Product与ProductLocation关联查询
解决方案
方法一:子查询实现(匹配原生SQL逻辑)
Doctrine QueryBuilder支持子查询,你可以先构建统计子查询,再关联到主查询中:
// 构建子查询:按productId分组计算location总和 $subQueryBuilder = $this->getEntityManager()->createQueryBuilder() ->select('pl.productId, SUM(pl.location) as count') ->from(ProductLocation::class, 'pl') ->groupBy('pl.productId'); // 主查询关联子查询,获取Product全量字段及统计值 $query = $this->createQueryBuilder('p') ->select('p, pc.count') ->leftJoin( sprintf('(%s)', $subQueryBuilder->getDQL()), 'pc', 'WITH', 'pc.productId = p.id' ) ->getQuery() ->execute();
方法二:直接关联后分组聚合(更简洁)
利用已配置的一对多关联,直接关联ProductLocation后分组计算:
$query = $this->createQueryBuilder('p') ->select('p, COALESCE(SUM(pl.location), 0) as count') ->leftJoin('p.productLocations', 'pl') ->groupBy('p.id') ->getQuery() ->execute();
注意事项
- 确保Product实体中已正确配置一对多关联:
// Product.php /** * @ORM\OneToMany(targetEntity=ProductLocation::class, mappedBy="product") */ private $productLocations; COALESCE函数用于处理无关联ProductLocation时的null值,将其转为0- 分组需按Product主键(
p.id)进行,确保每个Product仅返回一条结果
内容的提问来源于stack exchange,提问作者Oleksandr
相关产品推荐
相关产品推荐

