1

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!

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

4 Comments

You forgot the paginate and OP didn't say he was using a Model for Thread ;)
Oh, I just forgot to. I am using a model for a thread of course.
But yeah, unfortunately this doesn't work with paginate() :(
Okay, I just used Laravel to manually build a paginator. Thank you Alexey!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.