繁体   English   中英

多角色多团队用户数据库设计

[英]User with multiple roles and multiple teams database design

我无法理解这个

我希望允许用户拥有多个角色和多个团队,并且可能在未来添加其他内容。

设计这个的最佳方法是什么?

Users
---------- 
user_id
first name
last name

roles
--------
role_id
user_id (fk)
role_name

teams
-----
team_id
user_id (fk)
team name

something_else
------
selse_id
user_id (fk)
selse_name

然后像这样将所有内容分组在一张桌子上?

user_profile
---------------------
user_id - username - role_name - team_name - selse_name 

我不知道这是否应该没问题,因为我认为当我将数据传递给客户端的表单时它可能会变得复杂。

您的架构设计与我的做法类似。 您的问题在最后一点是关于将所有内容组合在一起的问题。

架构应该是:

create table users (
  user_id serial primary key,
  first_name text not null,
  last_name text not null,
  -- other columns here
);

create table roles (
  role_id serial primary key,
  role_name text not null unique,
  -- other columns here
);

create table user_role (
  id serial primary key,
  user_id int not null references users(user_id),
  role_id int not null references roles(role_id),
  unique(user_id, role_id)
);

类似地为teamssomething_else查找和连接表。

棘手的部分是提取这些数据以在 UI 中使用。 您将需要聚合属性,否则每个用户将有多个行。 例如,如果一个user有 3 个roles ,属于两个teams ,并且有 4 个something_else行,那么加入将为该user 24 个行。

假设您的 UI 是 Web 或一些现代工具包,检索此数据的最佳方式是 json。 PostgreSQL 可以为您构建该 json:

with aggs as (
  select u.user_id, u.first_name, u.last_name, 
         jsonb_agg(DISTINCT to_jsonb(r)) as roles,
         jsonb_agg(DISTINCT to_jsonb(t)) as teams,
         jsonb_agg(DISTINCT to_jsonb(s)) as something_else
    from users u
         left join user_role ur on ur.user_id = u.user_id
         left join roles r on r.role_id = ur.role_id
         left join user_team ut on ut.user_id = u.user_id
         left join teams t on t.team_id = ut.team_id
         left join user_something_else us on us.user_id = u.user_id
         left join something_else s on s.something_else_id = us.something_else_id
   group by u.user_id, u.first_name, u.last_name
)
select to_jsonb(aggs)
  from aggs
 where user_id = ?
; 
       

暂无
暂无

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

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