首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >复合外键没有唯一约束,PostgreSQL

复合外键没有唯一约束,PostgreSQL
EN

Stack Overflow用户
提问于 2021-04-23 00:41:37
回答 1查看 71关注 0票数 0

我正在尝试将一个关联表与另一个表联系起来。

代码语言:javascript
运行
复制
...

knex.schema.createTable("test", (table) => {
        table.integer("subject_id").unsigned().references("id").inTable("subject").notNullable();
        table.integer("duration_id").unsigned().references("id").inTable("duration").notNullable();
        table.unique(["subject_id", "duration_id"]);
    }),

    knex.schema.createTable("exam", (table) => {
        table.increments().notNullable();
        table.integer("subject_id").unsigned();
        table.integer("duration_id").unsigned();
        ...
        ...
        table.foreign(["subject_id", "duration_id"]).references(["subject_id", "duration_id"]).inTable("test");
    }),

...

抛出以下错误:

代码语言:javascript
运行
复制
migration failed with error: alter table "exam" add constraint "exam_subject_id_duration_id_foreign" foreign key ("subject_id", "duration_id") references "test" ("subject_id", "duration_id") 
- there is no unique constraint matching given keys for referenced table "test"

对这两列使用unique或primary key约束会导致相同的错误。这是与knex相关的错误吗?

EN

回答 1

Stack Overflow用户

发布于 2021-04-23 21:04:44

在unique约束之后移动外键约束解决了这个问题。虽然我不知道确切的原因。

代码语言:javascript
运行
复制
...

knex.schema.createTable("test", (table) => {
        table.integer("subject_id").unsigned().notNullable();
        table.integer("duration_id").unsigned().notNullable();
        table.unique(["subject_id", "duration_id"]);
  
        table.foreign("subject_id").references("id").inTable("subject");
        table.foreign("duration_id").references("id").inTable("duration");
    }),

    knex.schema.createTable("exam", (table) => {
        table.increments().notNullable();
        table.integer("subject_id").unsigned();
        table.integer("duration_id").unsigned();
        ...
        ...
        table.foreign(["subject_id", "duration_id"]).references(["subject_id", "duration_id"]).inTable("test");
    }),

...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67217470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档