我使用的是Laravel和MySQL,我有一个表帖子,它代表用户可以对其进行评论的帖子,现在我想按每个帖子的评论数量按上升/降序排序,我如何在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');
}
发布于 2014-10-14 23:50:41
您可以这样做,但现在您可以从数据库中获得所有条目。如果您有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
不是一个好主意,您应该使用参数sortBy,正如我所展示的
发布于 2014-10-14 22:59:42
我想我想出了一个解决办法:
$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();
https://stackoverflow.com/questions/26375845
复制