简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM