Laravel命令由hasmany关系

编程入门 行业动态 更新时间:2024-10-18 08:32:09
本文介绍了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关系

本文发布于:2023-10-24 20:10:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令   关系   Laravel   hasmany

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!