I have a User
entity with one-to-many
relationship with Certificate
entity (one user might have multiple certificates). A Certificate
has a startDate
and endDate
which determine their period of validity. I need filter all the users, that have expired certificates and have no active certificates.
An active certificate - c.startDate <= :today AND c.endDate > :today
An expired certificate - c.endDate <= :today
.
I now how to do it in plain SQL:
SELECT
u.user_id
FROM `User` u JOIN `Certificate` c ON c.user_id = u.user_id
GROUP BY u.user_id
HAVING SUM(c.end_date > :today) = 0
Now I'm trying to port the SQL query to Doctrine QueryBuilder syntax:
$qb = $this->createQueryBuilder();
$qb
->from('SomeNS:User', 'u')
->select('u')
->join('u.certificates', 'c')
->groupBy('u.id')
->having('SUM(c.endDate > :today) = 0')
->setParameter('today', $today);
But an error occurs:
Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '<'
It looks like the conditions in the SUM function aren't understood by Doctrine.
Please help to figure out how one can use conditions in SUM function or point me out what I do wrong.
Here is a concrete answer using the expr() method of queryBuilder:
---
->having(
$qb->expr()->andx( // this is the "AND" in between the sums
$qb->expr()->lte( // this is the "<="
...(your SUM here, after you fix the logic),
0
),
$qb->expr()->eq( // this is the "="
...(your SUM here, after you fix the logic),
0
)
)
)
Once you get those "SUM" conditions right, you put them in the placeholders and it should work.