問題描述
我有兩個 eloquent 模型 Threads
和 Comments
,每個線程都有很多評論.
I have two eloquent models Threads
and Comments
, each thread hasMany comments.
在列出線程時,我需要按 created_at 降序對線程進行排序.因此,我需要在 Comments
中使用 created at
對線程進行排序.
While listing the threads, i need to order the threads by the created_at descending. So , i need to sort the threads using created at
in Comments
.
顯然點符號對這種排序沒有幫助,我如何正確排序線程?
Apparently dot notation isn't helpful in ordering this way, how do i order the Threads correctly ?
$Threads= Thread::all()->orderBy("comment.created_at","desc")
推薦答案
了解 Laravel 的預加載是如何工作的很重要.如果我們急切加載您的示例,Laravel 首先獲取所有線程.然后它獲取所有評論并將它們添加到線程對象.由于使用了單獨的查詢,因此無法按注釋對線程進行排序.
It's important to understand how Laravel's eager loading works. If we eager load your example, Laravel first fetches all threads. Then it fetches all comments and adds them to the threads object. Since separate queries are used, it isn't possible to order threads by comments.
您需要改用連接.請注意,我在此示例中猜測您的表/列名稱.
You need to use a join instead. Note that I'm guessing at your table/column names in this example.
$threads = Thread::leftJoin('comment', 'comment.thread_id', '=', 'thread.id')
->with('comments')
->orderBy('comment.created_at', 'desc')
->get();
自從您加入后,您可能需要手動指定列以選擇您的表格列名.
Since you're joining, you might need to manually specify columns to select your tables column names.
$threads = Thread::select('thread.*')->leftJoin('comment', 'comment.thread_id', '=', 'thread.id')
->with('comments')
->orderBy('comment.created_at', 'desc')
->get();
這篇關于Laravel 按 hasmany 關系排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!