Laravel 2查询不起作用

时间:2017-05-29 11:48:29

标签: php laravel laravel-5 eloquent

我想将一个组分配给具有角色学生并且还具有特定选定组的用户。有一个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); 

3 个答案:

答案 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);