【发布时间】:2020-03-21 04:03:44
【问题描述】:
假设有一个Post 模型。它在其模型中定义了一个名为comments() 的hasMany 关系。
我正在尝试:
- 获取 cmets 的计数
- 属于一组特定的帖子,由 id 数组定义
- cmets 在特定日期范围内发布的位置
我认为以下方法会起作用:
$ids = [1, 2, 3, 4];
$results = Post::whereIn('id', $ids)
->with(['comments'])
->whereHas('comments', function($q) {
$q->whereMonth('created_at', Carbon::now()->month);
})
->withCount('comments')
->get();
然后做
$count = array_sum($results->pluck('comments_count')->toArray());
查询的结果确实包含comments_count,所以它可以工作,$count 也可以工作。
但是子查询中的日期范围没有被应用,它计算所有个cmets。我错过了什么?
【问题讨论】: