Doctrine2 QueryBuilder subquery with SUM?
-
26-10-2019 - |
Question
I'm trying to get Hotels from my database that have enough beds (user specifies guest count parameter). The query should look like this:
SELECT h.* FROM Hotel AS h
WHERE
(SELECT SUM(r.guestCount * r.count)
FROM Room AS r
WHERE r.hotel_id = h.id) >= $questCount
The above query contains subquery in the where clause. I've read doctrine's QueryBuilder documentation and I don't know how to make subquery in QB.
All I have now is:
$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder()
->select('h')
->from('AAAHotelsBundle:Hotel', 'h')
->where(.........???...........);
Any ideas what to do next?
Of course I simplified the problem (the query itself is much more complex). I use Symfony2.
Solution
I think this DQL will help you
SELECT h, SUM(r.guestCount * r.count) as TSUM FROM Hotel h JOIN h.room r
WHERE TSUM >= :questCount
OTHER TIPS
DQL is not a solution in my case. I do really need to use QueryBuilder. I've asked the same question on Google Groups and here is the solution:
$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder()
->select('h')
->from('AAAHotelsBundle:Hotel', 'h')
->join('Room', 'r')
->groupBy('h')
->having('SUM(r.guestCount * r.count) >= :guestCount')
->setParameter("guestCount", $guestCount);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow