Laravel带有所有评论和子评论的计数



我使用Laravel 8和withCount属性来获取在我的产品模型上发布的所有评论的数量。这些评论也包含子评论。现在我想得到每个产品的发表评论和儿童评论的数量。。。

我的评论表:id, page_status_id, user_id, commentable_type, commentable_id, content

我的孩子评论表:id, page_status_id, user_id, comment_id, content

这是我的product模型中的comments关系:

public function comments()
{
return $this->morphMany('AppModelsComment', 'commentable')->orderBy('id');
}

这是我的withCount函数:

public function publishedComments()
{
return $this->comments()->where('page_status_id', PageStatus::getIdByStatus('publish'));
}

统计发表的评论很容易。。。但是,我如何计算一个产品的所有发布评论和儿童评论?

有什么想法吗?我尝试了使用inner join的原始SQL语句,但这也是错误的方法。。

问候并感谢

您应该构建一个递归关系查询。在递归查询中,您试图选择所有子项及其后代。这方面的一个例子就是雄辩。

当你试图计算孩子的孩子时,你需要访问后代。在下面的代码中,我试图通过(allComments(函数递归地查询关系。这意味着,您可以获得所有家长和孩子的评论。在这里,您通过调用with并传递allComments方法来创建一个递归函数。

public function comments()
{
return $this->morphMany('AppModelsComment', 'commentable')->orderBy('id');
}
public function allComments()
{
return $this->comments()->with('allComments');
}

您可以将allComments与关系计数一起使用,如Product::withCount('allComments')

最新更新