嗨,我只是想获得该角色的权限,我正在尝试关注
$r = Role::find(1);
dd($r->permissions);
上面的脚本没有返回任何权限,但是您可以看到下表中有数据。我也尝试跟随但没有运气
$role = Role::with('permissions')->where('id', 1)->first();
如您所见,表中有数据
表格: tes_permissions
表格: tes_roles
表格: tes_permission_role
以下是模型
class Permission extends Model
{
protected $table = 'tes_permissions'
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
还有
class Role extends Model
{
protected $table = 'tes_roles';
public function permissions() {
return $this->belongsToMany('App\Permission', 'tes_permission_role', 'permission_id', 'role_id');
}
}
有人可以请我指导可能是什么问题,
答案 0 :(得分:0)
您在belongsToMany()
中混合了属性的顺序。第三个参数是为定义关系的模型指定ID。因此更改为以下内容:
public function permissions() {
return $this->belongsToMany('App\Permission', 'tes_permission_role', 'role_id', 'permission_id');
}
在Permission
模型上,也要进行肯定定义。
public function roles()
{
return $this->belongsToMany('App\Role', 'tes_permission_role', 'permission_id', 'role_id');
}