dqwh2717 2017-04-17 10:52
浏览 172
已采纳

Symfony Doctrine - 查询之后的OrderBy

I'd like to order only the result of the previous main query.

I want the top 10 most viewed articles then ordered it by "addedAt date" DESC.

I'm aware of functions such as orderBy or even addOrderBy but it's not what I need here or I'm not implementing it correctly.

Example to get the top 2 on 5 articles :

  • name : a || views : 100 || addedAt : 10/04/2017
  • name : b || views : 10 || addedAt : 17/04/2017
  • name : c || views : 50 || addedAt : 15/04/2017
  • name : d || views : 25 || addedAt : 12/04/2017
  • name : e || views : 200 || addedAt : 05/04/2017

I extract first the most views :

  1. Article e
  2. Article a

And then orderedIt by addedAt date DESC (most recent) :

  1. Article a
  2. Article e

My query :

public function findMostViewed($limit=10, $asArray=false)
{
        $qb = $this->createQueryBuilder('n')
            ->orderBy('n.nbViews', 'DESC')
            //->addOrderBy('n.addedAt', 'DESC')
            ->getQuery()
            ->setMaxResults($limit);

        return ($asArray) ? $qb->getResult(Query::HYDRATE_ARRAY) : $qb->getResult();
}

If I knew how to do a preSelectQuery it would have probably solve the problem ...

I thought to an SQL query :

SELECT ...
FROM ...
WHERE id IN(SELECT id FROM News ORDER BY nbViews DESC LIMIT 10)
ORDER BY addedAt DESC
  • 写回答

4条回答 默认 最新

  • duanpei4455 2017-04-18 19:12
    关注

    Based on Veve's answer, I changed the WHERE IN condition and managed to make it work.

    public function findMostViewed($limit=10, $asArray=false)
    {
            $subqb = $this->createQueryBuilder('nn')
                ->orderBy('nn.nbViews', 'DESC')
                ->getQuery()
                ->setMaxResults($limit);
    
            $qb = $this->createQueryBuilder('n')
                ->where('n.id IN (:ids)')
                ->setParameter('ids', array_values($subqb->getResult()))
                ->orderBy('n.addedAt', 'DESC')
                ->getQuery();
    
            return ($asArray) ? $qb->getResult(Query::HYDRATE_ARRAY) : $qb->getResult();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办