saralee
saralee

Reputation: 1

(LARAVEL) Two ORDER BY and a LIMIT

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

Upvotes: 0

Views: 2153

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

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');

Upvotes: 1

Related Questions