我有两个雄辩的模特Threads
and Comments
,每个帖子都有很多评论。
在列出线程时,我需要按created_at降序对线程进行排序。所以,我需要使用对线程进行排序created at
in Comments
.
显然点符号对于以这种方式排序没有帮助,我如何正确排序线程?
$Threads= Thread::all()->orderBy("comment.created_at","desc")
了解 Laravel 的急切加载是如何工作的很重要。如果我们急切地加载您的示例,Laravel 首先会获取所有线程。然后它获取所有评论并将它们添加到线程对象中。由于使用单独的查询,因此不可能通过注释对线程进行排序。
您需要改用联接。请注意,我在本示例中猜测您的表/列名称。
$threads = Thread::leftJoin('comment', 'comment.thread_id', '=', 'thread.id')
->with('comments')
->orderBy('comment.created_at', 'desc')
->get();
由于您要加入,您可能需要手动指定列来选择表列名称。
$threads = Thread::select('thread.*')->leftJoin('comment', 'comment.thread_id', '=', 'thread.id')
->with('comments')
->orderBy('comment.created_at', 'desc')
->get();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)