2

How would I run a subquery on withCount()?

I have a query I want to run for multiple counts, each with their own subqueries.

Here is an example of something that I'm looking for:

$date_from = Carbon::parse('1/1/2018');
$date_to = Carbon::parse('1/2/2018');

$models = Model::query()
    ->withCount('relation1', function (Builder $query) use ($date_from, $date_to) {
        $query->whereBetween('relation1.date1', [$date_from, $date_to])
              ->where('value1', true);
    })
    ->withCount('relation2', function (Builder $query) use ($date_from, $date_to) {
        $query->whereBetween('relation2.date2', [$date_from, $date_to])
              ->where('value2', false);
    })
    ->withCount('relation3', function (Builder $query) use ($date_from, $date_to) {
        $query->whereBetween('relation3.date3', [$date_from, $date_to]);
    });

How do I do this so it will correctly grab the model counts based on the subquery per relation?

1
  • Can you include the raw MySQL you intend to run, and maybe add some sample data? Commented Oct 23, 2018 at 2:06

1 Answer 1

7

I think you need to pass the sub-queries as associative array values:

https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models

E.g.

$date_from = Carbon::parse('1/1/2018');
$date_to = Carbon::parse('1/2/2018');

$models = Model::withCount([
        'relation1' => function (Builder $query) use ($date_from, $date_to) {
            $query->whereBetween('relation1.date1', [$date_from, $date_to])
                  ->where('value1', true);
        }, 
        'relation2' => function (Builder $query) use ($date_from, $date_to) {
            $query->whereBetween('relation2.date2', [$date_from, $date_to])
                  ->where('value2', false);
        },
        'relation3' => function (Builder $query) use ($date_from, $date_to) {
            $query->whereBetween('relation3.date3', [$date_from, $date_to]);
        }
    ])->get();
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.