【发布时间】:2021-06-30 14:55:05
【问题描述】:
我有users 表,其中有city_id,cities 表中的每个城市都有state_id。如何让任何州的用户使用city_id?
这是我的代码:
$users = User::role('company')
->when((int) $state, function ($query, $state) {
// here query
})
->when((int) $city, function ($query, $city) {
return $query->where('city_id', $city);
})
->get();
我试过了:
$users = User::role('company')
->when((int) $state, function ($query, $state) {
$cities = City::where('state_id', $state)
->pluck('id')
->toArray();
return $query->whereIn('city_id', $cities);
})
->when((int) $city, function ($query, $city) {
return $query->where('city_id', $city);
})
->get();
这是可行的,但是如何在不使用City 模型进行新查询的情况下正确执行此查询?
【问题讨论】:
标签: laravel eloquent relationship laravel-8