Laravel order by hasmany relationship(Laravel 按 hasmany 关系排序)
问题描述
我有两个 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 关系排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 按 hasmany 关系排序
基础教程推荐
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01