繁体   English   中英

跨 4 个表的多对多关系

[英]Many-to-Many Relationships across 4 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)

组与资源和角色具有多对多的关系。 所以我有以下联结表。

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)

这是问题:

组内的任何给定角色都应仅对分配给该组的资源具有权限。

我不完全确定 model 在group_resourcegroup_role关系上下文中rolespermissionsresources之间的关系的最佳方法是什么。

任何建议将不胜感激。

谢谢。

这是一个可能的解决方案,具有一定程度的冗余。

groups (id (PK), name, level)
roles (group_id (FK for groups) ,num_role, name) with PK (group_id, num_role)
users (id (PK), name, group_id, num_role) with (group_id, num_role) FK for roles
resource_types (id (PK), name)
group_resources (resource_type_id (FK for resource_types), group_id (FK for groups) with PK both the attributes
permissions (resource_type_id (FK for resource_types), group_id, num_role, description)  with (group_id, num_role) FK for roles

使用此解决方案,应用程序必须在插入权限期间检查资源是否出现在权限中指定的 group_id 中,通常带有触发器。

消除所有这些冗余的一种方法(但在我看来这是一个不太令人满意的设计),是消除关系group_resources ,因为所有信息都可以通过权限找到。

-- 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM