首页 > 解决方案 > 使用 laravel eloquent 计算给定帖子中评论的回复数

问题描述

我在下面有一个示例评论表:

id  | parent_id | post_id
 1      0            1
 2      0            1
 3      1            1
 4      2            1
 5      1            1

我想要实现的是根据 post_id 获取所有评论(parent_id=0),并同时计算总回复数。执行查询时,应显示如下结果:

 id 1 has 2 replies
 id 2 has 1 reply

下面是我的示例查询,它从给定的帖子中获取所有评论,但问题是,我不确定如何在一个查询中同时计数。

 Comment::where('parent_id', '=', 0)
          ->where('post_id', $postId)
          ->get();

有人知道如何解决这个问题吗?

标签: laravel

解决方案


您可以在 Comment 模型类中定义方法。如下:

public function replies()
{
    return $this->hasMany('App\Models\Comment','parent_id');
}

然后您可以使用以下代码获取回复数:

$comments = Comment::where('parent_id', '=', 0)
      ->where('post_id', $postId)
      ->withCount('replies')
      ->get();

在这种情况下,您可以使用以下代码访问评论数量:

foreach ($comments as $comment){
    $countOfReplies = $comment->replies_count;
}

我希望它有帮助


推荐阅读