gpt4 book ai didi

php - Laravel withCount() 子查询

转载 作者:行者123 更新时间:2023-12-02 14:55:53 25 4
gpt4 key购买 nike

如何在 withCount() 上运行子查询?

我有一个查询要针对多个计数运行,每个计数都有自己的子查询。

这是我正在寻找的东西的示例:

$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]);
});

我该怎么做才能根据每个关系的子查询正确获取模型计数?

最佳答案

我认为您需要将子查询作为关联数组值传递:

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

例如

$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();

关于php - Laravel withCount() 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52940125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com