How to order by count in Doctrine 2?

元气小坏坏 提交于 2019-11-28 06:58:20

what is the error you get when using COUNT(b.id) AS count? it might be because count is a reserved word. try COUNT(b.id) AS idCount, or similar.

alternatively, try $qb->addOrderby('COUNT(b.id)', 'DESC');.

what is your database system (mysql, postgresql, ...)?

There are many bugs and workarounds required to achieve order by expressions as of v2.3.0 or below:

  1. The order by clause does not support expressions, but you can add a field with the expression to the select and order by it. So it's worth repeating that Tjorriemorrie's own solution actually works:

    $qb->select('b.year, COUNT(b.id) AS mycount')
       ->from('\My\Entity\Album', 'b')
       ->where('b.year IS NOT NULL')
       ->orderBy('mycount', 'DESC')
       ->groupBy('b.year');
    
  2. Doctrine chokes on equality (e.g. =, LIKE, IS NULL) in the select expression. For those cases the only solution I have found is to use a subselect or self-join:

    $qb->select('b, (SELECT count(t.id) FROM \My\Entity\Album AS t '.
                    'WHERE t.id=b.id AND b.title LIKE :search) AS isTitleMatch')
       ->from('\My\Entity\Album', 'b')
       ->where('b.title LIKE :search')
       ->andWhere('b.description LIKE :search')
       ->orderBy('isTitleMatch', 'DESC');
    
  3. To suppress the additional field from the result, you can declare it AS HIDDEN. This way you can use it in the order by without having it in the result.

    $qb->select('b.year, COUNT(b.id) AS HIDDEN mycount')
       ->from('\My\Entity\Album', 'b')
       ->where('b.year IS NOT NULL')
       ->orderBy('mycount', 'DESC')
       ->groupBy('b.year');
    

If you want your Repository method to return an Entity you cannot use ->select(), but you can use ->addSelect() with a hidden select.

$qb = $this->createQueryBuilder('q') ->addSelect('COUNT(q.id) AS HIDDEN counter') ->orderBy('counter'); $result = $qb->getQuery()->getResult();

$result will be an entity class object.

David

Please try this code for ci 2 + doctrine 2

$where = " ";

$order_by = " ";
$row = $this->doctrine->em->createQuery("select a from company_group\models\Post a " 
            .$where." ".$order_by."")
            ->setMaxResults($data['limit'])
            ->setFirstResult($data['offset'])
            ->getResult();`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!