Laravel命令由hasmany关系 [英] Laravel order by hasmany relationship

查看:1735
本文介绍了Laravel命令由hasmany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个雄辩的模型线程评论,每个线程都有很多评论。

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关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆