Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit results of a left-join with Doctrine (DQL)

In a symfony 2 application, I have 2 entities mapped by a oneToMany relation (user and rendezvous). I'm trying to search into my user entity and join the last rendezvous for each user found. The idea is something like that :

    $qb = $this->createQueryBuilder('p');

    $qb->select('p.id, p.last_name, p.first_name')
       ->leftJoin('p.rendezvous', 'i')
            ->select('i.date')
            ->where('i.user = p.user')
            ->orderBy('i.date', 'DESC')
            ->setFirstResult(0)
            ->setMaxResults(1)                
       ->where('p.user IN ('.$users.')')
       ->orderBy('p.last_name', 'ASC')
       ->addOrderBy('p.first_name', 'ASC');

I should have results like :

1, Ben, Tooch, 2014-10-15 18:45:00
7, John, Snow, 2014-10-16 17:15:00
...

I tried to use the paginator function but without any success.
Thank you very much for your help.

like image 383
ArGh Avatar asked Oct 16 '14 10:10

ArGh


2 Answers

As I add some more columns to get, I had to find another way to do it. I finally got a working DQL query :

$qb->select('p.id, p.last_name, p.first_name, r.date, r.othercolumn')
    ->leftJoin('p.rendezvous', 'r', 'WITH', 'p.id = r.user AND r.date = (SELECT MAX(r2.date) FROM \App\YourBundle\Entity\Rendezvous as r2 WHERE r2.user = p.id)')               
    ->where('p.user IN ('.$users.')')
    ->orderBy('p.last_name', 'ASC')
    ->addOrderBy('p.first_name', 'ASC')
    ->groupBy('p.id');
like image 141
ArGh Avatar answered Oct 18 '22 03:10

ArGh


try groupBy the entity you want to setMaxResults on.

like image 29
Sam Shaba Avatar answered Oct 18 '22 02:10

Sam Shaba