(laravel)两个ORDER BY子句和一个LIMIT

This is some sorting:

  1. I want to list 20 best posts based on "views".
  2. then, sort it based on "created_at".

How to do it?

Heres my current code (which work, but doesnt sort by "created_at"):

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

You can write this. Hopefully this will solve your problem

$this->data['today_post'] = 
Posts::orderBy('views', 'desc')
->orderBy('created_at', 'desc')
->whereDate('created_at', Carbon::today()->toDateString())
->limit(20)
->get();

Also add use Carbon\Carbon; at the beginning of your controller.

Get a collection from database first

$x = Posts::whereRaw('created_at >= NOW() - INTERVAL 1 DAY')->orderBy('views', 'desc')->limit(20)->get();

Then sort the collection

Descending:

$this->data['today_post'] = $x->sortByDesc('created_at'); 

Ascending:

$this->data['today_post'] = $x->sortBy('created_at'); 

You can simply sort the result collection. Keeping your code, add the following:

$this->data['today_post'] = $this->data['today_post']->sortBy('created_at');