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

标签 database laravel eloquent relationship

如何使用 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/

相关文章:

database - 有效存储和查询GPS坐标

database - 为什么函数结果保存较晚?

Laravel 7.24 如果用户登录,如何更改导航栏的颜色

php - Eloquent laravel 模型空 id

php - 关系的 Eloquent 查询范围

MySQL 检查 3 个或更多连续(特定)条目

database - 从 subselect 语句结果数组更新 select 语句

mysql - 一般错误 : 1366 Incorrect integer value:

javascript - 在javascript数组中动态添加数据

php - 为什么QueryBuilder忽略我的输入参数?