【问题标题】:Count and order by relation with Laravel and Eloquent与 Laravel 和 Eloquent 的关系计数和排序
【发布时间】:2017-10-28 13:59:59
【问题描述】:

如何使用 Eloquent 从 post 中计算 comments 的数量,并按 comments 的数量排序 posts

我的代码是这样的:

class Post extends Model
{
    protected $table = 'posts';

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

我需要以一种优雅的方式检索按 cmets 数量排序的帖子集合,因此我不希望使用像 DB::select(select count(comment.post_id), post.id from posts left join comments on posts.id = comments.post_id group by post.id order by count(post.id)) 这样的东西;

【问题讨论】:

    标签: database laravel eloquent relationship


    【解决方案1】:

    您可以使用withCount 检索关系计数并使用orderBy(*_count) 对其进行排序。类似的,

    Post::withCount('comments')->orderBy('comments_count', 'desc')->get()
    

    【讨论】:

    • 谢谢,我使用了 dd($posts) 并注意到确实有一个名为 cmets_count 的新属性。这正是我想要的。
    猜你喜欢
    • 2021-01-25
    • 1970-01-01
    • 2021-07-14
    • 2015-01-29
    • 1970-01-01
    • 2017-08-22
    • 2015-07-05
    • 2017-07-12
    • 2017-05-07
    相关资源
    最近更新 更多