Laravel MySQL orderBy 计数

问题描述 投票:0回答:2

我正在使用 Laravel 和 MySQL,并且我有一个表 post 代表用户可以对其发表评论的帖子,现在我想按每个帖子的评论数量按升序/降序对帖子进行排序,我该怎么做这是 Laravel 中的吗?我不想在 post 表中添加一个字段来跟踪每个帖子的评论数量,因为每次添加/删除评论或评论的评论时手动更新该字段会让我发疯......

这就是我创建posts表和comments表的方式:

Schema::create('posts', function($table) {
    $table->increments('id');
    $table->string('title', 100)->unique();
    $table->string('content', 2000);
    $table->timestamps();
});
Schema::create('comments', function($table) {
    $table->increments('id');
    $table->string('content', 2000);
    $table->unsignedInteger('post_id');
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade')->onUpdate('cascade');
    $table->unsignedInteger('parent_id')->nullable();
    $table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade')->onUpdate('cascade');
    $table->timestamps();
});

这就是我在帖子模型中设置帖子和评论之间关系的方法:

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

并在评论模型中:

public function post() {
    return $this->belongsTo('Post', 'post_id');
}
laravel laravel-4 count sql-order-by eloquent
2个回答
4
投票

您可以按照您所展示的那样进行操作,但现在您可以从数据库中获取所有条目。如果您有 100 个帖子,每个帖子有 100 条评论,那么您将从数据库中获得 10000 行,只是为了对您的帖子进行排序(我假设您不想在排序时显示这些评论)。

您可以添加到您的帖子模型:

public function commentsCountRelation()
{
    return $this->hasOne('Comment')->selectRaw('post_id, count(*) as count')
        ->groupBy('post_id');
}

public function getCommentsCountAttribute()
{

    return $this->commentsCountRelation ?
        $this->commentsCountRelation->count : 0;
}

现在你可以使用:

$posts = Post::with('commentsCount')->get()->sortBy(function($post) {
    return $post->comments_count;
});

升序排序或

$posts = Post::with('commentsCount')->get()->sortBy(function($post) {
    return $post->comments_count;
}, SORT_REGULAR, true);

降序排序。

顺便说一句,使用

sortBy
和后来的
reverse
不是一个好主意,你应该使用参数来排序,正如我所展示的那样


1
投票

我想我已经想出了一个解决方法:

$posts = Post::with('comments')->get()->sortBy(function($post) {
    return $post->comments->count();
});

此条按评论数升序排列,如果您想按降序排列,请执行以下操作:

$posts = Post::with('comments')->get()->sortBy(function($post) {
    return $post->comments->count();
})->reverse();
© www.soinside.com 2019 - 2024. All rights reserved.