Brammz
Brammz

Reputation: 389

Sequelize migration gives 'ERROR: Cannot add foreign key constraint'

I'm trying to create two tables using Sequelize migrations, Organisations and OrganisationTypes. However, when I do the migrate to create the Organisations table I get an ERROR: Cannot add foreign key constraint. I don't see anything that could be wrong, like a type or name mismatch.

Here are the two migrations (1: OrganisationTypes; 2: Organisations):

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'
    }
  });
}

Upvotes: 0

Views: 1133

Answers (1)

Nae
Nae

Reputation: 15345

Configuration seems to be contradicting itself:

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

Upvotes: 1

Related Questions