Let's say there's a Post model. It has a hasMany relationship called comments() defined in its model.
I'm trying to:
- Get the count of comments
- That belongs to a specific set of Posts, defined by an array of ids
- Where the comments are posted in a certain date range
I thought the following would work:
$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();
And then do
$count = array_sum($results->pluck('comments_count')->toArray());
The result of the query does include comments_count so that's working, and $count works as well.
But the date range in the subquery is not applied, it counts all comments. What am I missing?