gpt4 book ai didi

php - Laravel 5.1 用户、角色和操作

转载 作者:可可西里 更新时间:2023-10-31 23:38:58 28 4
gpt4 key购买 nike

我正在使用 Laravel 5.1 创建一个包含用户角色操作 的应用程序。

表格设置如下:

用户

id    name
1 John Smith
2 Fred Smith

角色

id    name
1 Administrator
2 Customer

角色用户

user_id    role_id
1 1
2 1

Action

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 表列出了应用程序上所有可能的操作(即 url 或路由)。

action_role 是一个将action 链接到role 的数据透视表。

总结一下:

  • 用户有角色
  • 角色有行动
  • 一个用户可以有多个角色
  • 一个角色可以有很多 Action

如果用户有权查看当前页面,我想要一个中间件设置来检查页面加载。为此,我需要能够访问用户操作,使用如下调用:

$user->roles()->actions();

我如何建立 Eloquent 关系来支持这种呼吁?

更新

我的关系在我的模型中是这样设置的:

用户

/**
* 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');
}

Action

/**
* The roles that belong to the action.
*
* @return Object
*/
public function roles()
{
return $this->belongsToMany('App\Models\User\Role');
}

最佳答案

Eloquent 没有跨 2 个数据透视表的 HasManyThrough 关系。


1.您可以通过惰性渴望加载角色和 Action ,然后提取它们来获取 Action :

$actions = $user->load('roles.actions')->roles->pluck('actions')->collapse()->unique();

2.您可以使用 whereHas 约束直接在数据库中检查操作:

$allowed = $user->roles()->whereHas('actions', function ($query) use ($action) {
$query->where('name', $action);
})->exists();

关于php - Laravel 5.1 用户、角色和操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32551662/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com