我有一个包含项的表,一个用户可以有多个项,但同时只能有一个活动项.然而,@@unique个文档告诉所有字段must be not-null,这意味着用户只能有两项:one enabled and one disabled.
Here我发现我需要创建另一个包含pointer to Item和isActive值的表,但您不能确保只启用了一项.
我不想在这里使用空值,并且postgres连接器没有复合约束.你知道解决方案吗?
我有一个包含项的表,一个用户可以有多个项,但同时只能有一个活动项.然而,@@unique个文档告诉所有字段must be not-null,这意味着用户只能有两项:one enabled and one disabled.
Here我发现我需要创建另一个包含pointer to Item和isActive值的表,但您不能确保只启用了一项.
我不想在这里使用空值,并且postgres连接器没有复合约束.你知道解决方案吗?
这solution you linked个可以用来工作:
您不能确保只启用了一个项目
您101通过将唯一约束添加到那个"带指针的TrueRow表"来确保只启用了一项:demo
create table users(id int primary key);
insert into users values (1),(2);
create table test2(
id int primary key,
userid int not null references users(id),
misc text);
insert into test2 (id,userid,misc) values
(1, 1, 'a'),
(2, 1, 'b'),
(3, 1, 'c');
create table true_row(
fk_userid int not null references users(id) unique,
fk_test2_id int not null references test2(id) );
insert into true_row (fk_userid,fk_test2_id) values (1,3);
既然第三个条目被选为唯一行,其中isactive
将是true
,那么表将不允许"激活"另一个条目:
insert into true_row (fk_userid,fk_test2_id) values (1,2);
--ERROR: duplicate key value violates unique constraint "true_row_fk_userid_key"
--DETAIL: Key (fk_userid)=(1) already exists.
通常,您可以使用partial unique index:demo
create table test(
userid int,
isactive boolean,
misc text);
create unique index my_partial_unique
on test (userid)
where isactive is true;
where
条件阻止该索引约束isactive
设置为false
或null
的记录.它仅在设置为true
时适用,即每个userid
只允许一个这样的条目.
insert into test values
(1, false, 'a'),
(1, false, 'b'),
(1, true, 'c');
insert into test values
(1, true, 'd');
--ERROR: duplicate key value violates unique constraint "my_partial_unique"
--DETAIL: Key (userid)=(1) already exists.
update test
set isactive=true
where userid=1 and misc='b';
--ERROR: duplicate key value violates unique constraint "my_partial_unique"
--DETAIL: Key (userid)=(1) already exists.
遗憾的是,Prisma还不支持该特性(#3076,#6974),但您可以使用edit it into a migration.