Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Doctrine Query Builder Where last in arraycollection

I want to use symfony's query builder and add a where to the last item in an array collection

$query = $em->getRepository('RlBookingsBundle:Booking')->createQueryBuilder('b')
        ->select('b, v, c, ca, q')
        ->leftJoin('b.vehicle', 'v')
        ->leftJoin('b.customer', 'c')
        ->leftJoin('c.address', 'ca')
        ->leftJoin('b.quote', 'q')
        ->leftJoin('b.history', 'h') //This is an array collection
        ->orderBy('b.edited', 'DESC')
    ;

I want to use only the latest value from history as it is a log but only the most recent entry is valid

->where('h.status IN (:status)')
  ->setParameter('status', [7]);

Will return all results with h.status = 7 but I would like it to only query the most recent result. Is there anyway to do this?

I tried a groupby on the history field but this seems to groupby with data from the first entry, even if I add an orderby to it.

like image 683
user1806445 Avatar asked Nov 18 '25 07:11

user1806445


1 Answers

If the results you get are already ok, but you only want the first, you could just use

...
->setMaxResults(1)
...

If you want to order by history ID desc, you may want to add another orderBy clause before the existing one

...
->orderBy('h.id', 'DESC')
->orderBy('b.edited', 'DESC')
...

If it's more complex than that, I strongly suggest you perform a separate query to get the desired record(s) from history, and THEN use it as a filter, instead of the leftJoin.

like image 105
Francesco Abeni Avatar answered Nov 20 '25 19:11

Francesco Abeni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!