KNEX 和 MYSQL - 错误:ER_CANNOT_ADD_FOREIGN:无法添加外键约束

cne*_*ebs 4 javascript mysql knex.js

我正在将一个整体重构为微服务,并将其中一个的数据库切换到 MySQL。我正在使用 knex.js 来清理查询。我需要建立 3 个表。其中一个表只有三列:它自己的 id 和两个外键 id:来自其他两个表的每一个。

当尝试构建 knex.js 查询来构建表时,我在标题中收到错误。

我尝试使用可对 knex.js 查询进行的各种修改来重新安排我的查询,并尝试使用原始 mysql 外键查询。错误仍然存​​在。这是我的js代码:

const knex = require('knex') (CONFIG);

// Build images table
const imagesSchema = () => {
  knex.schema.createTable('images', (table) => {
    table.integer('id').primary();
    table.string('name');
    table.string('src');
    table.string('alt');
    table.string ('category');
    table.string('subCategory');
  })
  .then(console.log('test'));
};

// Build users table
const usersSchema = () => {
  knex.schema.createTable('users', table => {
    table.increments('id').primary();
    table.string('session', 64).nullable();
  })
  .then(console.log('users schema built into DB!'))
  .catch( error => {console.log('cant build the users schema!\n', error)})
}

// Build userhistory table
const userHistorySchema = () => {
  knex.schema.createTable('userhistory', table => {
    table.increments('id').primary();
    table.integer('userid').nullable();
    table.integer('imageid').nullable();

    // add foreign keys:
    table.foreign('userid').references('users.id');
    table.foreign('imageid').references('images.id');
  })
  .then(console.log('userhistory schema built into DB!'))
  .catch( error => {console.log('cant build the userhistory schema!\n', error)})
}
Run Code Online (Sandbox Code Playgroud)

我希望使用 userhistory.userid 列创建表以指向 users.id 列,并让 userhistory.imageid 列指向 images.id 列。相反,我收到此错误:

Error: ER_CANNOT_ADD_FOREIGN: Cannot add foreign key constraint

code: 'ER_CANNOT_ADD_FOREIGN',
  errno: 1215,
  sqlMessage: 'Cannot add foreign key constraint',
  sqlState: 'HY000',
  index: 0,
  sql: 'alter table `userhistory` add constraint `userhistory_userid_foreign` foreign key (`userid`) references `users` (`id`)'
Run Code Online (Sandbox Code Playgroud)

这些表是在我希望的位置没有外键的情况下创建的。

Sun*_*yle 9

对于 MySQL,外键需要定义为unsigned().
所以你的userhistory模式需要像这样设置:

knex.schema.createTable('userhistory', table => {
    table.increments('id').primary();
    table.integer('userid').unsigned().nullable();
    table.integer('imageid').unsigned().nullable();

    // add foreign keys:
    table.foreign('userid').references('users.id');
    table.foreign('imageid').references('images.id');
  })
  .then(console.log('userhistory schema built into DB!'))
  .catch( error => {console.log('cant build the userhistory schema!\n', error)})
}
Run Code Online (Sandbox Code Playgroud)