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

Doctrine2 DQL Syntax error when ordering by count

这是 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;

当我执行这段代码时出现错误

Error: Expected end of string, got '('

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

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

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

希望对您有所帮助