database - Many-to-Many Relationships across 4 Tables
问题描述
I'm implementing a role base access control system, for which have the following database tables.
groups
---------
id (PK)
name
level
resources
---------
id (PK)
name
roles
---------
id (PK)
name
permissions
-----------
id (PK)
name
description
users
-----------
id (PK)
name
group_id(FK - references id on groups)
role_id(FK - references id on roles)
Groups has a many-to-many relationship with Resources and Roles. So I have the following junction tables.
group_resource
---------------
group_id(FK - references id on groups)
resource_id(FK - references id on resources)
group_role
---------------
group_id(FK - references id on groups)
role_id(FK - references id on roles)
Here is the issue:
Any given role within a group should have permissions for resources assigned to that group only.
I'm not entirely sure what would be the best way to model the relationship between roles
, permissions
, and resources
in the context of group_resource
and group_role
relationships .
Any suggestions will be highly appreciated.
Thanks.
解决方案
-- Group GRP exists.
--
group {GRP}
PK {GRP}
-- Role ROL exists.
--
role {ROL}
PK {ROL}
-- Resource RES exists.
--
resource {RES}
PK {RES}
-- Role ROL exists within group GRP.
--
group_role {GRP, ROL}
PK {GRP, ROL}
FK1 {ROL} REFERENCES role {ROL}
FK2 {GRP} REFERENCES group {GRP}
-- Group GRP is assigned resource RES.
--
group_resource {GRP, RES}
PK {GRP, RES}
FK1 {GRP} REFERENCES group {GRP}
FK2 {RES} REFERENCES resource {RES}
-- Permission PER exists.
--
permission {PER}
PK {PER}
-- Permission PER is granted to role ROL
-- in group GRP for resource RES.
--
group_resource_permission {GRP, RES, ROL, PER}
PK {GRP, RES, ROL}
FK1 {GRP, RES} REFERENCES group_resource {GRP, RES}
FK2 {GRP, ROL} REFERENCES group_role {GRP, ROL}
FK3 {PER} REFERENCES permission {PER}
-- User USR is assigned role ROL in group GRP.
--
user {USR, GRP, ROL}
PK {USR}
FK1 {ROL} REFERENCES role {ROL}
FK2 {GRP} REFERENCES group {GRP}
-- User USR in role ROL of group GRP,
-- has permission PER to resource RES.
--
CREATE VIEW user_resource_permission
AS
SELECT u.USR
, x.RES
, x.PER
, u.GRP
, u.ROL
FROM user as u
JOIN group_resource_permission as x ON x.GRP = u.GRP
AND x.ROL = u.ROL ;
笔记:
All attributes (columns) NOT NULL
PK = Primary Key
AK = Alternate Key (Unique)
SK = Proper Superkey (Unique)
FK = Foreign Key
推荐阅读
- vue.js - Axios PUT 对 DRF Api 的请求通过,但未更新
- aws-cdk - 如何在 aws cdk 中使用自定义资源将文件上传到 s3 存储桶
- highcharts - Highcharts 8 - 在窗口调整大小时更改图表类型
- flutter - 如何确定 Flutter Web 应用是在手机还是 PC 上运行?
- algorithm - 如何正确编号两个字母字符?
- javascript - MongooseError [CastError]:模型“residence”的路径“_id”的值“5f37f59e549a291510f1c0dd”转换为 ObjectId 失败
- php - 从 Laravel 6 升级到 Laravel 7 的问题
- macos - Brew 安装 Octave - 权限被拒绝
- c++ - cpp中元素删除后的迭代器
- flutter - TextStyle.dart 引发的异常断言失败:第 936 行 pos 12: 'a == null || b == 空 || a.inherit == b.inherit': 不正确