gpt4 book ai didi

Knex.js - 外键约束形成不正确

转载 作者:行者123 更新时间:2023-12-05 06:35:50 28 4
gpt4 key购买 nike

我正在尝试使用 Knex.js 查询生成器构建数据库迁移,但是我收到以下与外键关系相关的错误:

Knex:warning - migrations failed with error: alter table `presentations` add constraint presentations_owner_id_foreign foreign key (`owner_id`) references `users` (`user_id`) - ER_CANT_CREATE_TABLE: Can't create table `application`.`#sql-35c_6a` (errno: 150 "Foreign key constraint is incorrectly formed")

这是presentations 表的迁移:

exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('presentations', function(table) {
table.increments('presentation_id');
table.string('title', 255);
table.integer('owner_id');
table.boolean('is_live');
table.timestamps();

table.foreign('owner_id').references('user_id').inTable('users');
})
]);
};

这是 users 表的迁移:

exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('users', function(table) {
table.increments('user_id');
table.string('first_name');
table.string('last_name');
table.string('email_address').unique();
table.string('password');

...

table.timestamps();
})
]);
};

不同的数据类型是否有问题?我正在尝试在 integerincrements 类型之间建立关系。

最佳答案

问题是 users.user_idpresentations.owner_id 有不同的类型。

// users table
table.increments('user_id'); // generates an unsigned integer

// presentations table
table.integer('owner_id'); // generates a signed integer

解决方案是使引用主键的列明确无符号。

table.integer('owner_id').unsigned();

// or: create column and relation in one go
table.integer('owner_id').unsigned().notNullable().references('users.user_id');

另请参阅:https://github.com/knex/knex/issues/245#issuecomment-619245125

顺便说一句:SQLite 要么不关心,要么有不同的类型在起作用。我们后来才开始针对 MariaDB 进行测试时才发现这一点。

关于Knex.js - 外键约束形成不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49482477/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com