Latest

Tuesday, July 11, 2017

Laravel Eloquent: Nested Query Builder?

Asked by: Hillcow


Is there any way I could perfrom this DB query with Eloquent instead?

DB::table(DB::raw('(select * from threads order by id limit 20) th'))->orderBy('votes')->paginate(10)

Basically I want to order the threads by votes, but I don't want to request all the threads in the table for that, but only the 20 recent ones.

thank you!


Answers

Answered by: Alexey Mezenin at 2017-07-11 08:06PM Accepted



Since you want to get latest 20 threads and then sort them by votes, you could use sortByDesc() method:

$threads = Thread::latest()->take(20)->get();
$orderedThreads = $threads->sortByDesc('votes');



Source

No comments:

Post a Comment

Adbox