【问题标题】:Laravel OrderBy comments in postsLaravel OrderBy 帖子中的评论
【发布时间】:2014-05-10 15:44:09
【问题描述】:

我有帖子和 cmets 表,当然 cmets 属于帖子。 我现在想用 eloquent 按 cmets 的数量对帖子进行排序。 我如何在 laravel 中做到这一点?

我尝试按日期订购:

Post::orderBy('created_at', 'DESC')->paginate(6);

我想要相同的,但按 cmets 排序,在其他数据库上,但它们在模型中连接。

编辑:

我现在有这个查询:

$post = Post::
        join('comments', 'comments.post_id' , '=', 'posts.id')
        ->groupBy('posts.id')
        ->orderBy(DB::raw('COUNT(posts.id)'))
        ->paginate(6);

{{ $post->author }} 作品... 但我无法从刀片中获得例如 {{ $post->comment->count()}}。在我之前的查询(上图)中它有效。不知道为什么。

【问题讨论】:

  • 这可能对您问题的第一部分有所帮助:stackoverflow.com/questions/19555259/laravel-4-sorting-data
  • 感谢您的帮助。很高兴看到这一点,但是当我这样做时,我无法在刀片中使用 eloquent,例如:$post->author(来自用户数据库)当我以这种方式对其进行排序时,似乎 eloquent 链接已损坏。
  • 您可以发布您正在使用的查询吗?
  • 当然,我编辑了第一篇文章。你可以看看。
  • 下面的代码将在 PHP 中进行排序以及相当多的子查询来获取计数,这肯定会比在 MySQL 中效率低,但它确实提供了很好的 (并且可读)代码:$posts = Post::all()->sortByDesc(function ($item) { return $item->comments()->count(); });为了减少子查询的数量,虽然它使用更多的内存,您可以执行以下操作:$posts = Post::with('comments')->get()->sortByDesc(function ($item) { return $item->comments->count(); });

标签: sorting laravel comments eloquent posts


【解决方案1】:

This answer 提供帮助。

您应该可以使用Collection 的sortBy() 和count() 方法相当容易地做到这一点。

$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
{
    return $hackathon->participants->count();
});

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2017-03-03
    • 2013-04-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多