我有两个雄辩的模型线程和评论,每个线程都有很多评论。
I have two eloquent models Threads and Comments , each thread hasMany 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();自从加入以来,您可能需要手动指定列来选择表列名。 / p>
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关系
发布评论