Laravel 使用城市 ID 按州获取用户
Laravel get users by state using city id
我有 users
table 其中有 city_id
而 cities
table 中的每个城市都有 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
模型进行新查询的情况下正确执行此查询?
用户和城市的关系你建立了吗?它应该是这样的:
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
您可以使用该关系获取用户 where has 属于该州的城市:
$users = User::role('company')
->when((int) $state, function ($query)use ($state) {
return $query->whereHas('city',function ($query)use ($state){
$query->where('state_id',$state);
});
})
->when((int) $city, function ($query)use($city) {
return $query->where('city_id', $city);
})
->get();
您可以使用 Laravel HasManyThough
假设你有一个州,每个州有很多城市,每个城市有很多用户
那么在状态模型中,可以添加这个函数
public function users()
{
return $this->hasManyThrough(User::class, City::class);
}
此函数将return所有用户处于给定状态
示例:
$state = State::first();
$users = $state->users;
有关更多信息,请阅读 docs
我有 users
table 其中有 city_id
而 cities
table 中的每个城市都有 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
模型进行新查询的情况下正确执行此查询?
用户和城市的关系你建立了吗?它应该是这样的:
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
您可以使用该关系获取用户 where has 属于该州的城市:
$users = User::role('company')
->when((int) $state, function ($query)use ($state) {
return $query->whereHas('city',function ($query)use ($state){
$query->where('state_id',$state);
});
})
->when((int) $city, function ($query)use($city) {
return $query->where('city_id', $city);
})
->get();
您可以使用 Laravel HasManyThough
假设你有一个州,每个州有很多城市,每个城市有很多用户
那么在状态模型中,可以添加这个函数
public function users()
{
return $this->hasManyThrough(User::class, City::class);
}
此函数将return所有用户处于给定状态
示例:
$state = State::first();
$users = $state->users;
有关更多信息,请阅读 docs