SQLSTATE [42S22]:找不到列:1054未知列'role_not'错误

时间:2020-01-28 15:15:45

标签: php laravel scope user-roles

我试图显示super_admin以外的用户,所以我在控制器中使用了whereRoleNot Function来隐藏super_admin。 我的用户模型:

public function scopeWhereRole($query, $role_name){
    return $query->whereHas('roles', function($q) use($role_name){
        return $q->whereIn('name', (array)'$role_name');
    });
}  //end of scopeWhereRole


public function scopeWhereRoleNotIn($query, $role_name){
    return $query->whereHas('roles', function($q) use($role_name){
        return $q->whereNotIn('name', (array)'$role_name');
    });
}  //scopeWhereRoleNotIn end

和用户控制器索引方法:

public function index()
 {
     //

     $users= User::whereRoleNot('super_admin')->paginate(3);
     return view('dashboard.users.index', compact('users'));
 }  //end of index

2 个答案:

答案 0 :(得分:3)

核心问题是使用范围时遇到了错字,但是由于您为范围命名的方式,它仍然是有效的where{column}子句。

Laravel具有动态功能,例如where{column}($search),它为提供的where值和{column}值构造一个简单的$search子句。举个例子:

$users = User::whereRoleNot('super-admin');

whereRoleNot尝试为该列创建一个where子句(在您的情况下为role_not(由字符串RoleNot动态构造),而您的数据库表没有有此专栏。

只需使用普通的where子句:

$users = User::where('role', '!=', 'super_admin')->paginate(3);

编辑:如果要使用作用域,建议您稍微更改一下名称:

public function scopeRoleIn($query, $role_name){
  return $query->whereHas('roles', function($q) use($role_name){
    return $q->whereIn('name', (array)$role_name); // Don't use `'` here
  });
} 

public function scopeRoleNotIn($query, $role_name){ 
  return $query->whereHas('roles', function($q) use($role_name){
    return $q->whereNotIn('name', (array)$role_name); // Don't use `'` here
  });
}

然后,按如下所示使用您的范围:

// $users = User::roleIn('super-admin')->paginate(3); // Etc...
$users = User::roleNotIn('super-admin')->paginate(3);

您可以使用scopeWhere...,但命名可能与Laravel的动态where{column}子句冲突,因此应避免使用它。

答案 1 :(得分:0)

SQLSTATE [42S22]:找不到列:1054未知列'role_not' 错误

这是因为Laravel希望您的User表中有一个列'role_not',因为您的本地范围被命名为scopeWhereRoleNotIn,删除了前缀范围,它的最终名称将变成WhereRoleNotIn,但是您将范围名称称为WhereRoleNot。现在您知道了为什么列'role_not'是错误的,因为Laravel期望您尚未使用本地范围。

现在,要调用此本地范围,您的查询应如下所示

public function index()
{
     $users= User::whereRoleNotIn('super_admin')->paginate(3);
     return view('dashboard.users.index', compact('users'));
 } 

即使“ where”是保留关键字,它也仍然有效

这很麻烦,您错过了调用本地范围的确切名称的原因,这就是Laravel将其视为查询生成器的where子句的原因。

请阅读文档local scope

相关问题