我正在使用Laravel 5.1创建一个应用程序,其中涉及到“用户”、“角色”和“操作”。
表格设置如下:
用户
id name
1 John Smith
2 Fred Smith
角色
id name
1 Administrator
2 Customer
role_user
user_id role_id
1 1
2 1
动作
id name description path
1 dashboard ability to access dashboard /admin
2 editAdmin ability to edit admins /admin/users/administrators/{id}/edit
action_role
action_id role_id
1 1
2 1
user
表包含站点上的所有用户,包括管理员和客户。
role
表包含用户可能拥有的所有角色。例如,管理员或客户。
role_user
表是将role
与user
联系起来的中间表。
action
表列出应用程序中所有可能的操作(即网址或路由)。
action_role
是一个中间表,将action
与role
相关联。
因此,总结如下:
- 用户拥有角色
- 角色拥有操作
- 一个用户可以拥有多个角色
- 一个角色可以拥有多个操作
我想设置一个中间件,在页面加载时检查用户是否有权限查看当前页面。为了做到这一点,我需要能够访问用户的操作,使用以下调用:
$user->roles()->actions();
如何设置我的 Eloquent 关系来支持这种调用?
更新:
我的模型中的关系设置如下:
User 模型:
/**
* The roles that belong to the user.
*
* @return Object
*/
public function roles()
{
return $this->belongsToMany('App\Models\User\Role')->withTimestamps();
}
角色
/**
* The actions that belong to the role.
*
* @return Object
*/
public function actions()
{
return $this->belongsToMany('App\Models\User\Action');
}
/**
* The users that belong to the role.
*
* @return Object
*/
public function users()
{
return $this->belongsToMany('App\Models\User\User');
}
操作
/**
* The roles that belong to the action.
*
* @return Object
*/
public function roles()
{
return $this->belongsToMany('App\Models\User\Role');
}