2017-05-29 102 views
1

我想将一个组分配给有角色学生并且也有特定选定组的用户。有一个用户表,它具有数据透视表:role_user和group_user角色和组表。下面是在那里我试图执行查询控制器代码:Laravel two wherehas查询不起作用

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

回答

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(); 
0

你缺少一个use声明带来$whereGroupId到范围为whereHas关闭。

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

$selectedGroup = $request->input('add-group'); 
$whereGroupId = $request->input('where-group'); 

$users = User::whereHas('roles', function ($query) { 
     return $query->where('name', 'student'); 
    }) 
    ->whereHas('groups', function ($query) use ($whereGroupId) { 
     return $query->where('id', $whereGroupId); 
    }) 
    ->get(); 

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

您有语法错误,并且缺少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); 
+0

assignGroup应该为用户分配一个组。然而,我得到了上述问题的解决方案,assignGroup出现了另一个问题。我只能将一个组只分配给一个用户,而不是像预期的那样多。我将就此发起另一个问题。 – Valentine

+0

通过对每个用户使用foreach并分别分配它们来解决assignGroup问题。 – Valentine