我要加载具有company_id
= 28
的用户。我放了where子句,但它不起作用,集合返回了所有记录。
MyController.php
public function index($type, $company_id = '')
{
$user = User::whereHas('roles', function ($query) use ($type) {
$query->where('name', '=', $type);
})->get();
$users = $user->load(['userSetting' => function ($query) {
$query->where('company_id', '28');
}]);
return response()->json($users);
}
User.php
public function userSetting()
{
return $this->hasOne('App\UserSettings', 'user_id');
}
答案 0 :(得分:0)
您可以使用filter:
filter方法使用给定的回调过滤集合,仅保留那些通过给定的真相测试的项。
例如:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all(); // [3, 4]
在您的控制器内:
public function index($type, $company_id = '')
{
$users = User::whereHas('roles', function ($query) use ($type) {
$query->where('name', '=', $type);
})->get();
//If you want to load the relationship with the users:
/*
$users = User::whereHas('roles', function($query) use ($type) {
$query->where('name', '=', $type)
})
->with('userSettings')
->get()
*/
$users = $users->filter($user){
return $user->userSettings->company_id == 28;
}
return response()->json($users);
}
希望有帮助。