我想将一个组分配给具有角色学生并且还具有特定选定组的用户。有一个users表,它有一个数据透视表: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);
答案 0 :(得分: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();
答案 1 :(得分: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);
答案 2 :(得分: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);