dongsiju1941 2017-04-20 15:17
浏览 182

(LARAVEL)两个ORDER BY和一个限制

This is some sorting:

  1. Get 20 posts sorted by "views".
  2. AFTER IT FINISH, then go to the next step.
  3. sort it by "created_at".

How to do it?

Heres my current code (which work, but I dont want to use SORTBY) for some reason sortby is not working for other project. if possible i want it to be as one eloquent query:

$this->data['today_post'] = Posts::orderBy('views', 'desc')->whereRaw('created_at >= NOW() - INTERVAL 1 DAY')->limit(20)->get();
$this->data['today_post'] = $this->data['today_post']->sortByDesc('created_at');

This code is not working, because LIMIT is usually applied as the last operation, so the result will first be sorted by "views" and "created_at" and then limited to 20. I dont want that. I want to sort and limit then after all is complete. I want to sort again the last time.

$this->data['today_post'] = Posts::orderBy('views', 'desc')->orderBy('created_at', 'desc')->whereRaw('created_at >= NOW() - INTERVAL 1 DAY')->limit(20)->get();

Thank you so much

  • 写回答

1条回答 默认 最新

  • doushi7819 2017-04-20 15:30
    关注

    You'll still need to use sortBy() or sortByDesc() if you want to use Eloquent. I've just tested this solution and it works perfectly:

    Posts::orderBy('views', 'desc')
         ->where('created_at', '>=', Carbon::now()->subDay())
         ->take(20)
         ->get()
         ->sortByDesc('created_at');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?