如何使用“明显的”与学说?

时间:2014-01-15 07:24:48

标签: php symfony doctrine-orm distinct distinct-on

我尝试在教条中使用“distinct 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();
    }
}

我如何实现以下查询?

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;

显然,使用查询构建器似乎无法执行此操作。我尝试以不同的方式重写我的查询:

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);

但是学说不支持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();
}

我认为唯一的解决方案是使用本机SQL查询。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-2)

只需删除on字词:

$queryBuilder->select('distinct r.parentId')
             ->orderBy('r.parentId')
             ->orderBy('r.date', 'DESC');