我正在尝试计算每个月的博客数量以及一次查询中每个博客的帖子数量:
Blog::withCount(['posts'])
->whereBetween('created_at', $this->currentRange())
->select(DB::raw("DATE_FORMAT(created_at, '%b') month"), DB::raw('COUNT(*) num'), DB::raw('SUM(posts_count) sum'))
->groupBy('month')
->get();
得到如下结果:
+---------+-------+--------+
| month | num | posts |
+---------+-------+--------+
| Jan | 10 | 5 |
| Feb | 20 | 6 |
| Mar | 30 | 7 |
+---------+-------+--------+
以下SQL由eloquent生成:
SELECT
DATE_FORMAT(created_at, '%b') MONTH,
COUNT(*) num,
SUM(posts_count) sum
FROM
`blogs`
WHERE
`created_at` BETWEEN 0001 -01 -01 00: 00: 00
AND 2023 -01 -05 21: 10: 59
AND `blogs`.`deleted_at` IS NULL
GROUP BY
`MONTH`
完全缺少 posts_count。我想我期待 Eloquent 魔法。有没有一种 Eloquent 方式来做到这一点?还是原始查询是前往此处的方式?
最佳答案
您可以使用子查询。
Blog::withCount(['posts'])
->select(DB::raw("DATE_FORMAT(blogs.created_at, '%b') month"), DB::raw('COUNT(*) num'), DB::raw("SUM(posts_count) sum"))
->join(DB::raw("(SELECT blog_id, SUM(posts.id) sum_posts FROM posts WHERE posts.created_at BETWEEN blogs.created_at AND blogs.created_at + INTERVAL 1 MONTH GROUP BY blog_id) as posts_per_blog"), function($join) {
$join->on('blogs.id', '=', 'posts_per_blog.blog_id');
})
->whereBetween('blogs.created_at', $this->currentRange())
->groupBy('month')
->get();
关于sql - 如何在 Laravel Eloquent 中使用 withCount 和 groupBy month?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75023938/