我正在使用 Laravel 和 MySQL,并且我有一个表post代表用户可以评论的帖子,现在我想按照每个帖子的评论数量按升序/降序对帖子进行排序,我该如何在 Laravel 中执行此操作?我不想添加字段post表来跟踪每个帖子的评论数量,因为每次添加/删除评论或评论的评论时手动更新该字段会让我发疯......
这就是我创建我的posts表和comments table:
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');
}
您可以按照您所展示的那样进行操作,但现在您可以从数据库中获取所有条目。如果您有 100 个帖子,每个帖子有 100 条评论,那么您将从数据库中获得 10000 行,只是为了对您的帖子进行排序(我假设您不想在排序时显示这些评论)。
您可以添加到您的 Post 模型中:
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
这不是一个好主意,您应该使用参数来排序,正如我所展示的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)