问题
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:
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();
来源:https://stackoverflow.com/questions/52940125/laravel-withcount-subquery