简体   繁体   English

laravel渴望加载与where子句不起作用的关系

[英]laravel eager loading relationship with where clause not working

I want to load that users that have a company_id = 28 . 我想加载具有company_id = 28 I put where clause but its not working, collection returning all records. 我把where子句但它不起作用,集合返回所有记录。

MyController.php 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 user.php的

public function userSetting()
{
   return $this->hasOne('App\UserSettings', 'user_id');
}

You can use filter : 你可以使用过滤器

The filter method filters the collection using the given callback, keeping only those items that pass a given truth test. filter方法使用给定的回调过滤集合,仅保留通过给定真值测试的项目。

For example: 例如:

$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
});
$filtered->all(); // [3, 4]

Within your controller: 在你的控制器内:

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

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM