【问题标题】:laravel eager loading relationship with where clause not workinglaravel 急切加载与 where 子句的关系不起作用
【发布时间】:2019-11-05 13:53:25
【问题描述】:

我想加载具有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');
}

【问题讨论】:

  • 你做的时候有没有结果:UserSettings::first();
  • @HCK 是的,我有
  • 另外,您有一个User 1-m UserSettings,所以您只想加载与UserSettings 中符合user_id=28 的单个记录链接的唯一/唯一用户的关系?跨度>
  • 怎么样:$query->where('userSetting.company_id', '28'); 作为急切加载条件? (我包括了关系名称)

标签: php laravel laravel-5 eloquent relationship


【解决方案1】:

你可以使用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);
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多