[英]Laravel withCount() subquery
How would I run a subquery on withCount()? 如何在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? 如何执行此操作,以便它将根据每个关系的子查询正确获取模型计数?
I think you need to pass the sub-queries as associative array values: 我认为您需要将子查询作为关联数组值传递:
https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models
Eg 例如
$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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.