【问题标题】:Laravel two wherehas queries not workingLaravel 两个 wherehas 查询不起作用
【发布时间】:2017-06-07 12:25:05
【问题描述】:

我想将一个组分配给具有角色学生并且还具有特定选定组的用户。有一个用户表,其中包含数据透视表:role_user 和 group_user 以及角色和组表。下面是我尝试执行查询的控制器的代码:

$this->validate($request, [
    'add-group'      => 'required',
    'where-group'    => 'required'
]);

$selectedGroup = $request->input('add-group');
$whereGroupId  = $request->input('where-group');
$users         = User::whereHas('roles', function($q) {
                     $q->where('name', 'student');
                 })->whereHas('groups', function($q) {
                     $q->where('id', $whereGroupId);
                 })->get();

$selectedGroup = Group::whereId($selectedGroup)->first();
$users->assignGroup($selectedGroup); 

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    您需要在查询的后半部分使用orWhereHas 子句。

    其次,您的 $whereGroupId 变量不在内部函数的范围内,请添加 use($whereGroupId) 语句以将其包含在函数的范围内。

    $users = User::whereHas('roles', function($q) {
        $q->where('name', 'student');
    })->orWhereHas('groups', function($q) use ($whereGroupId) { // <-- Change this
        $q->where('id', $whereGroupId);
    })->get();
    

    【讨论】:

      【解决方案2】:

      您有语法错误,并且缺少 use 以传递 whereGroupId。我不知道assignGroup 做了什么,但这应该可以修复您拥有的代码。

      $this->validate($request, [
          'add-group' => 'required',
          'where-group' => 'required'
      ]);
      
      $selectedGroup = $request->input('add-group');
      $whereGroupId = $request->input('where-group');
      
      $users = User::whereHas('roles', function ($q) {
              $q->where('name', 'student');
          })
          ->whereHas('groups', function ($q) use ($whereGroupId) {
              $q->where('id', $whereGroupId);
          })->get();
      
      $selectedGroup = Group::whereId($selectedGroup)->first();
      
      $users->assignGroup($selectedGroup);
      

      【讨论】:

      • assignGroup 应该为用户分配一个组。我得到了上述问题的解决方案,但是,assignGroup 提出了另一个问题。我只能将一个组分配给一个用户,而不是像预期的那样多。我将在同一问题上开始另一个问题。
      • 解决了 assignGroup 问题,方法是对每个用户使用 foreach 并单独分配。
      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 2017-11-26
      • 2021-05-25
      • 2015-07-29
      相关资源
      最近更新 更多