php - Laravel order by hasmany 关系

标签 php mysql laravel eloquent relationship

我有两个 Eloquent 模型 ThreadsComments ,每个线程都有很多评论。

在列出线程时,我需要按 created_at 降序排列线程。因此,我需要使用 Comments 中的 created at 对线程进行排序。

显然点符号对以这种方式排序没有帮助,我该如何正确排序线程?

$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();

关于php - Laravel order by hasmany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28634921/

相关文章:

php - 通过 AJAX 的 Laravel Route 调用获取错误的 URL 404(未找到)

php - 我可以通过哪种方式使用 Laravel Eloquent Relation 来解决我的问题

php - 为什么我在文本框中得到奇怪的值?

php - 从循环中获取元素的 ID

PHP 分页排序结果

mysql - SQL 查询中对象的上下文或命名空间

php - 从数据库计数

laravel - 转储优化的 Composer 自动加载器

php - Zend框架prepareStatementForSqlObject和execute不起作用

php - 11200 HTTP 检索失败