使用 laravel eloquent 计算给定帖子中评论的回复数量

smz*_*app 1 laravel

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

id  | parent_id | post_id
 1      0            1
 2      0            1
 3      1            1
 4      2            1
 5      1            1
Run Code Online (Sandbox Code Playgroud)

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

 id 1 has 2 replies
 id 2 has 1 reply
Run Code Online (Sandbox Code Playgroud)

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

 Comment::where('parent_id', '=', 0)
          ->where('post_id', $postId)
          ->get();
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

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

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

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

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

foreach ($comments as $comment){
    $countOfReplies = $comment->replies_count;
}
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助