指定外键时Knex迁移失败,提示数据类型不兼容
Knex+Postgres迁移报错:外键uuid与integer类型不兼容
我用Knex结合NodeJS构建Postgres数据库Schema,执行迁移时遇到外键错误。明明vehicle表的model_id和vehicle_model表的id都是uuid类型,但系统提示二者类型不兼容(uuid与integer),无法创建外键约束。
迁移函数代码:
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
问题原因与修复方法
问题出在外键关联的表没有指定schema。虽然你用withSchema("oem")切换了schema,但在定义外键时,inTable("vehicle_model")没有带上oem前缀,Knex会默认去public schema里找这个表。如果你的public schema里恰好存在一个旧的vehicle_model表,且它的id字段是integer类型,就会触发这个类型不兼容的错误。
修复方式很简单,在inTable里指定完整的schema.表名即可:
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("oem.vehicle_model"); // 这里加上schema前缀 table.integer("year").notNullable(); }); }
重新执行迁移即可解决这个问题。
内容的提问来源于stack exchange,提问作者Matthew G
相关产品推荐
相关产品推荐

