I'm trying to use a subquery in a IN statement in Doctrine2.
Here's what the raw SQL query should look like :
SELECT * FROM license
WHERE id
IN (SELECT id
FROM license
WHERE subscription = x
ORDER BY date DESC
LIMIT 5)
ORDER BY name ASC;
What I want to do is display the 5 last results ordered by name, so I have to first query the last 5 results and then order by name in the main query.
The problem is that I can't seem to LIMIT the inner query.
Here's my current code :
$qb = $this->createQueryBuilder('l');
$qb->select('l.id');
$qb = $this->whereSubscriptionId($qb, $subscription_id);
$qb = $this->offsetLimitOrder($qb, 0, 5, 'deliveryDatetime desc');
//Second Query, adds the "order by X"
$qb2 = $this->createQueryBuilder('l2');
$qb2->add('where', $qb2->expr()->in('l2.id', $qb->getQuery()->getDQL()));
if(isset($order)){
$order = explode(' ', $order);
$qb2->addOrderBy('l2.'.$order[0], $order[1]);
}
return $qb2->getQuery()
->getResult();
As you can see, I create my first query, I order and limit it (via a custom method) and then I try to use it in the second query.
However, it seems that the LIMIT is not part of the DQL statement because when I var_dump the first query's DQL, the LIMIT is absent, which means that it's completly ignored when I run $qb2->getQuery()->getResult();
I made it work by launching the first query and manually inputing the results in the second one, but it's ugly.
Any idea on how to do it properly ?
Thanks !
Unfortunately Doctrine does not support limit on nested queries. Even if you use 2 QueryBuilders and setMaxResults() on the inner QueryBuilder, it will simply be ignored.
The only way to do this at this time is to run 2 individual queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With