且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel雄辩:嵌套查询生成器?

更新时间:2022-10-23 21:20:10

由于你想获得最新的20个线程,他们通过投票,您可以使用 sortByDesc() 方法:

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


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!

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