我有一个包含项的表,一个用户可以有多个项,但同时只能有一个活动项.然而,@@unique个文档告诉所有字段must be not-null,这意味着用户只能有两项:one enabled and one disabled.

Here我发现我需要创建另一个包含pointer to ItemisActive值的表,但您不能确保只启用了一项.

我不想在这里使用空值,并且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设置为falsenull的记录.它仅在设置为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.

Node.js相关问答推荐

错误:找不到模块';/var/apps/前端/bash';

MongoDB如果文档S的字段小于另一个字段,则将该字段加一

如何在医学中按patientId查找一个并同时插入多个数据

为什么 Cors 在 NodeJS 中不起作用

在 Nest 项目上运行 Jest 测试时,我的文件无法找到一个在测试之外没有任何问题的模块

Node.js中使用ffmpeg如何获取视频截图的位置?

在生产环境中,Nest实例启动时抛出不完整的导入错误

AWS ECS 服务发现 Cors 问题?

在系统启动时启动本地 node 服务器

在 Atlas 触发器(Node JS)中正确初始化 Firebase 管理 SDK

baseurl64 缓冲区解码

在 Mongoose 中创建外键关系

如何在客户端使用 node.js 模块系统

create-react-app,安装错误(找不到命令)

如何在 node 中转义 shell 命令的字符串?

Javascript在try块内设置const变量

- configuration.output.path:提供的值public不是绝对路径!使用 Webpack

如何创建安全(TLS/SSL)Websocket 服务器

在 Node.js 中获取终端的宽度

我无法全局安装 nodemon,nodemon无法识别