按计数排序时,Doctrine2 DQL语法错误

时间:2016-09-07 00:15:34

标签: doctrine-orm dql

这是Doctrine Repository功能

public function mostReadArticleByUser($userId){
    $total = $this->createQueryBuilder('ar')
        ->select('ar.articleId', 'COUNT(ar)')
        ->where('ar.authorId = :userId')
        ->groupBy('ar.articleId')
        ->orderBy('COUNT(ar)', 'DESC')
        ->setMaxResults(1)
        ->setParameter('userId', $userId)
        ->getQuery()
        ->getResult();

    return $total;
}

应该等同于此查询

SELECT article_id, count(id)
    FROM profile_article_reads
    WHERE author_id = 2
    GROUP BY article_id
    Order by count(id) DESC
    LIMIT 1;

当我执行此代码时,我收到错误

  

错误:字符串的预期结束,得到'('

     

QueryException:SELECT ar.articleId,COUNT(ar)FROM   SciProfileBundle \ Entity \ ProfileArticleReads ar WHERE ar.authorId =   :userId GROUP BY ar.articleId ORDER BY COUNT(ar)DESC

1 个答案:

答案 0 :(得分:1)

计数功能接受一个字段,所以尝试使用

COUNT(ar.id)

而不是:

COUNT(ar)

使用别名可能更好地进行排序,例如:

public function mostReadArticleByUser($userId){
    $total = $this->createQueryBuilder('ar')
        ->select('ar.articleId', 'COUNT(ar.id) as total')
        ->where('ar.authorId = :userId')
        ->groupBy('ar.articleId')
        ->orderBy('total', 'DESC')
        ->setMaxResults(1)
        ->setParameter('userId', $userId)
        ->getQuery()
        ->getResult();

    return $total;
}

希望这个帮助