How to use "distinct on" with doctrine?

Alexandre picture Alexandre · Jan 15, 2014 · Viewed 7.1k times · Source

I try to use "distinct on" with doctrine but I get the following error:

Error: Expected known function, got 'on'

class Report extends EntityRepository
{
    public function findForList() {
        $queryBuilder = $this->createQueryBuilder('r');
        $queryBuilder->select('distinct on (r.parentId)')
                     ->orderBy('r.parentId')
                     ->orderBy('r.date', 'DESC');

        return $queryBuilder->getQuery()->getResult();
    }
}

How could I implement the following query?

select distinct on (r.parent_id)
    r.parent_id,
    r.id,
    r.name
from frontend.report r
order by r.parent_id, r.date desc;

Apparently it doesn't seem possible to do this with the query builder. I tried to rewrite my query in different ways:

select * from frontend.report r
where 
r.id in (
select distinct 
   (select r3.id from frontend.report r3
   where r3.parent_id = r.parent_id 
   order by r3.date desc limit 1) AS id
from frontend.report r2);

But doctrine doesn't support LIMIT:

public function findForList() {
    $qb3 = $this->_em->createQueryBuilder();
    $qb3->select('r3.id')
        ->from('MyBundle:frontend\report', 'r3')
        ->where('r3.parentId = r2.parentId')
        ->orderBy('r3.date', 'DESC')
        //->setMaxResults(1)
            ;

    $qb2 = $this->_em->createQueryBuilder();
    $qb2->select('(' . $qb3->getDql() . ' LIMIT 1)')
        ->from('MyBundle:frontend\report', 'r2')
        ->distinct(); // groupBy('r2.parentId')

    $queryBuilder = $this->createQueryBuilder('r');
    $queryBuilder->where(
        $queryBuilder->expr()->in('rlt.id', $qb2->getDql())
    );

    return $queryBuilder->getQuery()->getResult();
}

I think the only solution is to use native SQL queries.

Answer

jose.serapicos picture jose.serapicos · Oct 20, 2016

This response is for someone that yet looking for the solution in similar cases. If you need a sample "DISTINCT" you can use:

$queryBuinder->select('parentId')
             ->distinct('parentId');

but if you want a "DISTINCT ON" you should use Native SQL instead of Query Builder, check out the manual here: Doctrine Native SQL