2

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?

1 Answer 1

3

You will need to pass the same condition/subquery to the withCount method:

->withCount(['comments' => function($q) {
       $q->whereMonth('created_at', Carbon::now()->month);
    }])

https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_withCount

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.