gpt4 book ai didi

Laravel MySQL 按计数排序

转载 作者:行者123 更新时间:2023-12-04 12:20:41 25 4
gpt4 key购买 nike

我正在使用 Laravel 和 MySQL,我有一个表格帖子代表用户可以对其发表评论的帖子,现在我想按每个帖子的评论数量按升序/降序排列帖子,我如何在 Laravel 中执行此操作?我不想在帖子表中添加一个字段来跟踪每个帖子的评论数量,因为每次添加/删除评论或评论的评论时手动更新该字段让我发疯......

这是我创建帖子表和评论表的方式:

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();
});

这就是我在 Post 模型中设置帖子和评论之间关系的方式:
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不是一个好主意,你应该像我展示的那样使用参数来排序

关于Laravel MySQL 按计数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375845/

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