【问题标题】:Sequelize migration gives 'ERROR: Cannot add foreign key constraint'Sequelize 迁移给出“错误:无法添加外键约束”
【发布时间】:2019-05-22 14:58:08
【问题描述】:

我正在尝试使用 Sequelize 迁移、Organizations 和 OrganisationTypes 创建两个表。但是,当我进行迁移以创建 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'
    }
  });
}

【问题讨论】:

  • 为什么organisationTypeId既不能为空,又在父删除时应该设置为NULL
  • 嗯,这是一个非常好的问题......而且,还有解决方案,谢谢!

标签: javascript mysql sequelize.js


【解决方案1】:

配置似乎自相矛盾:

// ...
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

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多