首页 > 解决方案 > Sequelize 迁移给出“错误:无法添加外键约束”

问题描述

我正在尝试使用 Sequelize 迁移、组织和组织类型创建两个表。但是,当我进行迁移以创建 Organizations 表时,我得到一个ERROR: Cannot add foreign key constraint. 我没有看到任何可能出错的地方,例如类型或名称不匹配。

这是两个迁移(1:OrganizationTypes;2:Organizations):

up: (queryInterface, Sequelize) => {
  return queryInterface.createTable('OrganisationTypes', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      unique: true,
      type: Sequelize.INTEGER
    },
    name: {
      allowNull: false,
      unique: true,
      type: Sequelize.STRING
    }
  });
}
up: (queryInterface, Sequelize) => {
  return queryInterface.createTable('Organisations', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      unique: true,
      type: Sequelize.INTEGER
    },
    name: {
      allowNull: false,
      unique: true,
      type: Sequelize.STRING(60)
    },
    organisationTypeId: {
      allowNull: false,
      type: Sequelize.INTEGER,
      references: {
        model: 'OrganisationTypes',
        key: 'id'
      },
      onDelete: 'SET NULL'
    }
  });
}

标签: javascriptmysqlsequelize.js

解决方案


配置似乎自相矛盾:

// ...
organisationTypeId: {
  allowNull: false,         // <--- here it's not allowed to be null
  type: Sequelize.INTEGER,
  references: {
    model: 'OrganisationTypes',
    key: 'id'
  },
  onDelete: 'SET NULL'      // <--- yet here it's supposed to be set null upon parent deletion

推荐阅读