gpt4 book ai didi

database - 根据与 Laravel 和 Eloquent 的关系进行计数和排序

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:43 25 4
gpt4 key购买 nike

如何使用 Eloquent 计算来自 postcomments 的数量,并根据 comments< 的数量对 posts 进行排序?

我的代码是这样的:

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

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

我需要以优雅的方式检索按评论数量排序的帖子集合,因此我不想使用类似 DB::select(select count(comment.post_id), post.id from posts left 加入评论 posts.id = comments.post_id group by post.id order by count(post.id));

最佳答案

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

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

关于database - 根据与 Laravel 和 Eloquent 的关系进行计数和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com