Laravel 中间表(能自动插入数据吗)?
1》RBAC 数据库设计
Category(商户)表
字段名 | 数据类型 | 自增 |
---|---|---|
Id | Int(10) | 是 |
Name | Varchar(20) | |
roleId | Tinyint(1) | |
Password | Varchar(20) | |
Created_at | Timestamp | |
Updated_at | Timestamp |
Part(角色)表
字段名 | 数据类型 | 自增 |
---|---|---|
Id | Int(10) | 是 |
Name | Varchar(20) | |
Description | Varchar(20) | |
Created_at | Timestamp | |
Updated_at | Timestamp |
Category_part(用户角色)表
字段名 | 数据类型 | 自增 |
---|---|---|
Id | Int(10) | 是 |
category_id | Int(11) | |
part_id | Int(11) | |
Created_at | Timestamp | |
Updated_at | Timestamp |
Access(权限表)
字段名 | 数据类型 | 自增 |
---|---|---|
Id | Int(10) | 是 |
Title | Varchar(20) | |
Route | Varchar(255) | |
Created_at | Timestamp | |
Updated_at | Timestamp |
Part_access表(角色权限表)
字段名 | 数据类型 | 自增 |
---|---|---|
Id | Int(10) | 是 |
part_id | Int(11) | |
access_id | Int(11) | |
Created_at | Timestamp | |
Updated_at | Timestamp |
2》模型关联
public function parts()
{
return $this->belongsToMany(Part::class, 'part_category', 'category_id', 'part_id') ->withTimestamps();
}
// 1、需要的权限\ * 2、读取当前用户所拥有的权限* 3、再通过角色判断是否有当前需要的权限
public function hasPermission($permissionName)
{
foreach ($this->parts as $part)
{
if ($part->access()->where('title', $permissionName)->exists())
{
return true;
}
}
return false;
}
public function part()
{
return $this->belongsToMany(Part::class,'access_part','access_id','part_id');
}
//所属角色的用户
public function category()
{
return $this->belongsToMany(Category::class,'part_category','category_id','part_id');
}
//所属角色的权限
public function access()
{
return $this->belongsToMany(Access::class);
}
补充说明:
经手动在数据表(4张表)中添加对应的数据,再加上自己写的中间件,是可以判断当前登录用户是否有对应权限的。
中间件代码:
//把这个中间件放入路由组,把需要的验证的路由,放入这个中间组里
public function handle($request, Closure $next)
{
//获取当前路由的别名,如果没有返回 null
$part = \Route::currentRouteName();
// 判断权限表中这条路由是否需要验证
if ($access = Access::where('url', $part)->first()) {
// 当前用户不拥有这个权限的名字
if (! auth()->user()->hasPermission($access->title)) {
Alert::warning('您没有权限,请联系管理员!')->autoclose(3000);
return redirect('/companies');
}
}
return $next($request);
}
3》寻求帮助的问题(实际开发)
a、在新建角色---邦定权限时,怎样使---中间表(Part_access)能自动生成对应的数据?
b、在新建用户---选择角色时,怎样使---中间表(Category_part)能自动生成对应的数据?
c、怎样给一个用户设置为超级管理员?
本帖由 Summer
于 5年前 解除加精
推荐文章: