尝试从“用户”添加或检索“角色”时,我遇到以下错误。
SQLSTATE [42S22]:找不到列:1054未知列'roles.user_id' 在'where子句'(SQL:select * from
-------------- |id|name | -------------- |2 |rav (21) | -------------- |3 |nag (123)| --------------
whereroles
。roles
= 1和user_id
。roles
不是空限制1)
表
user_id
Role.php
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->timestamps();
});
}
user.php的
class Role extends Model
{
protected $fillable = ['name'];
public $timestamps = false;
public function users()
{
return $this->hasMany(User::class);
}
}
中间件/ CheckRole.php
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role_id', 'username', 'firstname', 'lastname', 'active', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->hasOne(Role::class);
}
private function checkIfUserHasRole($need_role)
{
return (strtolower($need_role) == strtolower($this->role->name)) ? true : null;
return $need_role;
}
public function hasRole($roles)
{
if (is_array($roles))
{
foreach ($roles as $need_role)
{
if ($this->checkIfUserHasRole($need_role))
{
return true;
}
}
}
else
{
return $this->checkIfUserHasRole($roles);
}
return false;
}
}
web.php
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$roles = $this->getRequiredRoleForRoute($request->route());
if ($request->user()->hasRole($roles) || !$roles){
return $next($request);
}
return redirect()->route('noPermissions');
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles'] : null;
}
}
答案 0 :(得分:1)
在User
类中,您使用了错误的关系方法。尝试更改
public function role()
{
return $this->hasOne(Role::class);
}
到
public function role()
{
return $this->belongsTo(Role::class);
}
正如the documentation所说。 hasOne
预计存在违规roles.user_id
。