Question

There is one-2-many relation between Property and Reservation. Property has column called 'nr_of_bookings'. I need DQL that will retrieve only the properties that has COUNT(Reservation) less than Property.nr_of_bookins.

An example: Some Property has nr_of_bookings = 3 . If it has 5 Reservations related, it will not be retrieved. But if it has 2 related Reservations, it will be retrieved.

I tried numerous combinations, but I miss something obviosly. I posted similar question here , but it is better to start from scratch. Thanks.

Was it helpful?

Solution

Have you tried:

'SELECT p FROM Product p WHERE SIZE(p.reservations) < p.nr_of_bookings'

EDIT: The above is for Doctrine 2. For Doctrine 1.2, looking at your code, I'm guessing your HAVING clause is referencing something that's not in a group by or the result of an aggregate function. Try something like this:

$q = PropertyTable::getInstance()
    ->createQuery('p') 
    ->select('p.*, COUNT(r.id) as num_of_reservations, SUM(p.nr_of_bookings) as num_bookings') 
    ->leftJoin('p.Reservation r') 
    ->groupBy('p.id') 
    ->having('num_of_reservations < num_bookings');

You're grouping by p.id so SUM(p.nr_of_bookings) will be equal to p.nr_bookings.

From the MySQL documentation:

The SQL standard does not permit the HAVING clause to name any column not found in the GROUP BY clause if it is not enclosed in an aggregate function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top