gpt4 book ai didi

php - Laravel 多个 withCount 在同一个关系上

转载 作者:可可西里 更新时间:2023-11-01 00:08:18 26 4
gpt4 key购买 nike

我需要计算来自相同关系的两个不同条件的结果,但它以相同的名称返回。

Model::where('types_id', $specialism_id)
->withCount(['requests' => function ($query) {
$query->where('type', 1);
}])
->withCount(['requests' => function ($query) {
$query->where('type', 2);
}])

我可以使用 $model->requests_count 访问 withCount,但是因为它正在查询相同的关系,所以它似乎覆盖了它:

select count(*) 
from `requests` where `requests`.`id` = `model`.`id`
and `type` = '1') as `requests_count`,
(select count(*) from `requests` where `requests`.`id` = `model`.`id`
and `type` = '2') as `requests_count`

如何为多个 withCount 指定名称?

最佳答案

现在你可以这样做了

Model::where('types_id', $specialism_id)
->withCount(['requests as requests_1' => function ($query) {
$query->where('type', 1);
}, 'requests as requests_2' => function ($query) {
$query->where('type', 2);
}])

关于php - Laravel 多个 withCount 在同一个关系上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985587/

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