简体   繁体   English

如何在学说上使用“与众不同”?

[英]How to use “distinct on” with doctrine?

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: 但是,该学说不支持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. 我认为唯一的解决方案是使用本机SQL查询。

This response is for someone that yet looking for the solution in similar cases. 此响应适用于在类似情况下仍在寻找解决方案的人。 If you need a sample "DISTINCT" you can use: 如果您需要样本“ DISTINCT”,则可以使用:

$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 但是,如果要“ DISTINCT ON”,则应使用本机SQL而不是查询生成器,请在此处查看手册: Doctrine本机SQL

Just remove the on word : 只是删除on字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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