laravel - 使用 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();
有人知道如何解决这个问题吗?
解决方案
您可以在 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;
}
我希望它有帮助
推荐阅读
- macos - 让 macOS 沙盒应用程序写入由我的非沙盒应用程序创建的文件
- php - 如何调用传递一些特定参数的 php 文件?
- cloudinary - Cloudinary 上传器无法处理大型视频
- c# - 如何获取使用自定义连接管理器定义的 SSIS 连接
- c# - 为什么每个[TestMethod]都会多次调用[TestClass]的构造函数?
- java - 尝试在 Android 中打开 excel 文件时不断收到 FileNotFound 异常
- r - 如何在 R 中按天按 UTC 时间戳分组
- elasticsearch - 弹性搜索嵌套聚合 - 文档中的方法不起作用
- javascript - 如何正确重新格式化 jQuery / JS 函数?
- amazon-ec2 - 如何解决/修复与正在运行的 Kubernetes pod 交互的问题(超时错误)?