【问题标题】:Knex migration is failing when specifying a foreign key指定外键时 Knex 迁移失败
【发布时间】:2022-11-30 13:34:45
【问题描述】:

我将 Knex 与 NodeJS 一起使用来构建模式,但在尝试运行迁移时收到错误消息。我在车辆表中指定的外键似乎有问题。 Knex 认为键之间的数据类型不同,而实际上它们显然不同。数据库在 Postgres 上运行。

这是我当前的迁移功能。

export function up(knex) {
  return knex.schema
    .createSchemaIfNotExists("oem")
    .withSchema("oem")
    .createTable("ktm", function (table) {
      table.string("model");
      table.integer("year");
      table.integer("category");
      table.string("diagram");
      table.string("sku");
      table.string("title");
      table.index(["model", "year", "sku"]);
    })
    .createTable("vehicle_model", function (table) {
      table.uuid("id", { primaryKey: true });
      table.string("title");
    })
    .createTable("vehicle", function (table) {
      table.uuid("id", { primaryKey: true });
      table.string("handle").notNullable();
      table.uuid("vendor_id").notNullable();
      table
        .uuid("model_id")
        .notNullable()
        .references("id")
        .inTable("vehicle_model");
      table.integer("year").notNullable();
    });
}

运行此命令会导致出现以下错误消息。

Key columns "model_id" and "id" are of incompatible types: uuid and integer.
error: alter table "oem"."vehicle" add constraint "vehicle_model_id_foreign" foreign key ("model_id") references "vehicle_model" ("id") - foreign key constraint "vehicle_model_id_foreign" cannot be implemented

【问题讨论】:

    标签: node.js postgresql knex.js


    【解决方案1】:

    发现我的问题。 改变了这个:

    .createTable("vehicle", function (table) {
          table.uuid("id", { primaryKey: true });
          table.string("handle").notNullable();
          table.uuid("vendor_id").notNullable();
          table
            .uuid("model_id")
            .notNullable()
            .references("id")
            .inTable("oem.vehicle_model"); // <<< specify schema before table
          table.integer("year").notNullable();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2017-04-12
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      相关资源
      最近更新 更多