laravel - 来自同一模型的多个模型的计数关系
问题描述
我有以下三个模型:用户、帖子和评论。一个用户可以有多个帖子,每个帖子可以有多个评论。
我想做的是:
- 获取属于特定用户的所有帖子的所有评论数
- 获取本月属于同一用户的所有帖子的所有评论数
- 起点是按 ID 发布的特定帖子(因此不是从用户 ID 开始)。
请参阅下面我现在所拥有的,这很有效。
我的问题是:是否可以将执行 ->sum() 的最后两行添加到查询中?
我认为这个查询已经很漂亮了,但它看起来会更好,但更重要的是,如果最后两行也包括在内,它会使缓存变得容易得多。
$post = Post::findOrFail($id);
$posts = Post::where('user_id', $post->user_id)
->withCount(['comments as comments_total'])
->withCount([
'comments as comments_this_month' => function ($q) {
$q->whereBetween('created_at',
[ Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth() ]
);
},
])->get();
});
$comments_this_month_count = $posts->sum('comments_this_month');
$comments_total_count = $posts->sum('comments_total');
解决方案
我可以只用两行代码提出更好的解决方案。
在模型中定义hasManyThrough
关系User
:
public function comments()
{
return $this->hasManyThrough(
Comment::class,
Post::class,
'user_id', // Foreign key on posts table...
'post_id' // Foreign key on comments table...
);
}
然后像这样调用它:
$comments_this_month_count = User::find($post->user_id)->comments()
->whereMonth('created_at', now()->month)->count();
$comments_total_count = User::find($post->user_id)->comments()->count();
推荐阅读
- symfony - 如何在将要在生产中呈现的模板中使用“dump()”twig 函数?
- python - CS50 面试问题 - 查找最长的子串递归之谜 - 为什么测试用例 #4 不起作用?
- postgresql - “重复键值违反唯一约束”在预先填充的 postgres 表中添加元素时暴露
- delphi - 为什么 FileAge 返回意外的值?
- r - 在 R 中获取最近 6 个月的数据
- google-apps-script - 如何将更新日志的最新项目放在谷歌电子表格的顶部
- django - 带有 Keycloak 和 Django 的 OIDC - 缺失状态
- javascript - 只能由登录用户编辑
- express - 没有错误消息或状态,只是被重新路由回我的登录
- java - 如何使用 Mockito 测试构建器 - Java