mysql - 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
但这也是错误的方式..
亲切的问候,谢谢
解决方案
您应该构建一个递归关系查询。在递归查询中,您尝试选择所有子项及其后代。此处以雄辩的方式回答了这方面的一个例子。
当您尝试计算孩子的孩子时,您需要访问后代。在下面的代码中,我试图通过 ( 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')
推荐阅读
- sql-server - 我们如何根据 Infor Syteline(9.00.03)ERP 中 RMA 行表单上的不同输入参数从多个表中填充下拉列表中的数据
- java - for循环中的Java8变量
- javascript - 按天计算分组日期的平均价格
- c# - 为什么我不能更改此数组中的元素
- javascript - 从 react-native 或 node.js 中的键盘电话中获取 1-9 位的响应
- azure - 为什么 azure app 服务响应 404?
- python - 将列表中的每个字符串连接到 Python 中的其他几个字符串
- javascript - 无法访问获取的数组元素
- javascript - 用于检查两个数组是否相等的 JavaScript 函数
- postgresql - 如何设置由EF核心代码创建的对象的默认所有者首先使用带有数据库凭证轮换的postgresql?