实体之间的OneToMany
关系:
Composer
> Soundtrack
Soundtrack
> SoundtrackRating
我希望按给定的Soundtrack
选择每个Composer
,并为每个SoundtrackRatings
支付Soundtrack
的费用。
在DQL
:
SELECT s.name, (SUM(r.rating)/COUNT(r.rating)) AS rating
FROM Soundtrack AS s
LEFT JOIN SoundtrackRating AS r
WHERE s.composer = :composer AND r.soundtrackId = s.id
GROUP BY s.id
ORDER BY rating DESC
然后我传递:composer
类型Composer
的实例:
$em->createQuery($dql)
->setParameter('composer', $composer)
->getResult();
然而,在查询结果中,无论Soundtrack
我作为参数传递,我都会收到所有$composer
个条目。唯一的区别是只能平均给定$composer
的评分,其余的平均值为0
。
此查询中的问题在哪里?
答案 0 :(得分:0)
想出来。从r.soundtrackId = s.id
子句中移除WHERE
并使用WITH
中的LEFT JOIN
代替:
SELECT s.name, (SUM(r.rating)/COUNT(r.rating)) AS rating
FROM Soundtrack AS s
LEFT JOIN SoundtrackRating AS r WITH r.soundtrackId = s.id
WHERE s.composer = :composer
GROUP BY s.id
ORDER BY rating DESC