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 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端