我正在创建AdminAuthenticated中间件
public function handle($request, Closure $next)
{
if (Auth::user()->role->name == 'customer') {
return redirect('/home')->with('message', 'You are not allowed to access');
}
return $next($request);
},我的问题是,当我使用雄辩的关系时,它会工作得很好,但是当我使用查询生成器时,它的抛出错误
这段代码工作
public function role(){
//this code work
return $this->belongsTo('App\Role');
}这段代码抛出错误为什么会发生,以及如何使用下面的代码(查询生成器)
public function role(){
//this code not work throw exception
return DB::table('users')
->join('roles', 'roles.id', '=', 'users.role_id')
->select('roles.*')
->where('users.id','=',$this->id);
}发布于 2020-06-03 09:46:16
由于这种关系是多到多的,所以...there是用户和角色表之间的一个枢轴表。
在“连接”中,您不能忽略枢轴表..。
如果您使用的是斯帕蒂
那么你的“加入”应该是:
public function role(){
return DB::table('users')
->join('model_has_roles',function($join){
$join->on('users.id', '=', 'model_has_roles.model_id')
where('model_has_roles.model_type','=',User::class);}) )
->join('roles','roles.id','=','model_has_roles.role_id')
->select('roles.*')
->where('users.id','=',$this->id);
}注意:我建议将方法重命名为“角色”,而不是“角色”。
https://stackoverflow.com/questions/62168683
复制相似问题