我刚刚为同事做了类似的事情。本质上,我制作了一个隐藏表,其中每个对(用户,角色)对都包含一行,并具有适当的约束。然后,用户表是隐藏表的视图,其中所有角色都组装到一个数组中。然后,我可以通过添加适当的规则来插入视图。方法如下:
trailer=# create table harvester (id int unique, label text);
CREATE TABLE
trailer=# insert into harvester values (1,'grain'), (2,'cricket');
INSERT 0 2
trailer=# create table donkey (id int, others int references
harvester(id));
CREATE TABLE
trailer=# create unique index donkey_ears on donkey (id, others);
CREATE INDEX
trailer=# create view combine as select id, array_agg(others) as others
from donkey group by id;
CREATE VIEW
trailer=# create rule combine_insert as on insert to combine do instead
(delete from donkey where donkey.id=new.id;insert into donkey select
new.id,unnest(new.others) );
CREATE RULE
trailer=# insert into combine values (1,'{1,2}');INSERT 0 2
trailer=# select * from combine ;
id | others
----+--------
1 | {1,2}
(1 row)
trailer=# insert into combine values (1,'{1,2}');
INSERT 0 2
trailer=# select * from combine ;
id | others
----+--------
1 | {1,2}
(1 row)
trailer=# insert into combine values (2,'{1,2,3}');
ERROR: insert or update on table "donkey" violates foreign key
constraint "donkey_others_fkey"
DETAIL: Key (others)=(3) is not present in table "harvester".
trailer=#
希望对您有所帮助。您可以提高效率,并根据需要添加更多规则。