在 Sequelize 中使每个用户 ID 的字段唯一?

Make field unique per user Id in Sequelize?

场景:

用户有3个选择,第1个选择,第2个选择,第3个选择。每个选择都保存在带有选择号和用户 ID 的数据库中。

如何进行唯一验证,使用户#11 不能有两个选择#2。

阅读文档,您似乎只能输入一栏,例如电子邮件。

这是你想要的吗?

CREATE UNIQUE INDEX idxu_user_choice ON my_table(choice_id, user_id);

SQL Fiddle

PostgreSQL 9.6 架构设置:

CREATE TABLE t
    ("user_id" int, "choice_id" int, "comment" varchar(8))
;
CREATE UNIQUE INDEX idxu_user_choice ON t(choice_id, user_id);

INSERT INTO t
    ("user_id", "choice_id", "comment")
VALUES
    (1, 1, 'azer'),
    (1, 2, 'zsdsfsdf'),
    (2, 1, 'sdghlk')
;

查询 1:

INSERT INTO t ("user_id", "choice_id", "comment")
VALUES (2, 2, 'dfgdfgh')

Results: 查询 2:

select * from t

Results:

| user_id | choice_id |  comment |
|---------|-----------|----------|
|       1 |         1 |     azer |
|       1 |         2 | zsdsfsdf |
|       2 |         1 |   sdghlk |
|       2 |         2 |  dfgdfgh |

查询 3:

INSERT INTO t ("user_id", "choice_id", "comment")
VALUES (1, 2, 'cvbkll')

Results:

ERROR: duplicate key value violates unique constraint "idxu_user_choice" Detail: Key (choice_id, user_id)=(2, 1) already exists.