Laravel 5.1用户,角色和操作 [英] Laravel 5.1 users, roles and actions
问题描述
我正在使用Laravel 5.1和 users , roles 和 actions 来创建应用程序.
I am creating an application using Laravel 5.1 with users, roles and actions.
表格设置如下:
用户
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
表包含该网站上的所有用户,包括管理员和客户.
The user
table holds ALL users on the site, including administrators and customers.
role
表包含用户可以拥有的所有可能角色.例如管理员或客户.
The role
table holds all the possible roles a user can have. For example Administrator or Customer.
role_user
表是将role
链接到user
的数据透视表.
The role_user
table is a pivot table which links role
to user
.
action
表列出了应用程序上所有可能的操作(即url或路由).
The action
table lists all of the actions possible (i.e. urls or routes) on the app.
action_role
是将action
链接到role
的数据透视表.
The action_role
is a pivot table which links action
to role
.
总结一下:
- 用户具有角色
- 角色有行动
- 用户可以扮演多个角色
- 一个角色可以有很多动作
我希望有一个中间件设置,可以检查用户是否有权查看当前页面的页面加载.为此,我需要能够使用如下调用来访问用户操作:
I want to have a middleware setup which checks on page load if the user has permissions to view the current page. In order to do this, I need to be able to access a users actions, using a call like this:
$user->roles()->actions();
我该如何建立雄辩的人际关系来支持这种通话?
How do I setup my eloquent relationships to support this kind of call?
更新
我的关系在模型中的设置方式如下:
My relationships are setup like so in my models:
用户
/**
* 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');
}
推荐答案
口才在2个数据透视表中没有HasManyThrough
关系.
Eloquent does not have a HasManyThrough
relationship across 2 pivot tables.
1..您可以通过懒惰地急于加载角色和动作,然后提取它们来获得动作:
1. You can get the actions by lazy eager loading the roles and actions, then extracting them:
$actions = $user->load('roles.actions')->roles->pluck('actions')->collapse()->unique();
2..您可以使用whereHas
约束直接在数据库中检查操作:
2. You can check the action directly in the database, using a whereHas
constraint:
$allowed = $user->roles()->whereHas('actions', function ($query) use ($action) {
$query->where('name', $action);
})->exists();
这篇关于Laravel 5.1用户,角色和操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!