首页 > 解决方案 > Laravel withCount 所有评论和子评论

问题描述

我正在使用 Laravel 8 和withCount属性来获取在我的产品模型上发布的所有评论的数量。这些评论也有子评论。现在我想获取每个产品的已发布评论和子评论的数量......

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

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

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

    public function comments()
    {
        return $this->morphMany('App\Models\Comment', 'commentable')->orderBy('id');
    }

这是我的withCount功能:

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

获取已发布评论的计数非常容易……但是如何获取产品的所有已发布评论和子评论的计数?

有任何想法吗?我尝试了一个原始的 SQL 语句,inner join但这也是错误的方式..

亲切的问候,谢谢

标签: mysqllaraveleloquentcountnested

解决方案


您应该构建一个递归关系查询。在递归查询中,您尝试选择所有子项及其后代。此处以雄辩的方式回答了这方面的一个例子。

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

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'commentable')->orderBy('id');
}

public function allComments()
{
    return $this->comments()->with('allComments');
}

您可以陪伴allComments关系计数,例如Product::withCount('allComments')


推荐阅读