i.brod
i.brod

Reputation: 4603

Sequelize migration fails with errno: 150 "Foreign key constraint is incorrectly formed"

I've created a table using this migration:

up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('articles', {
      id: { type: Sequelize.INTEGER, primaryKey: true,autoIncrement: true },
      title: { type: Sequelize.STRING },
      content: { type: Sequelize.TEXT },
      createdAt: {type:Sequelize.DataTypes.DATE},
      updatedAt: {type:Sequelize.DataTypes.DATE}
    },
 );

Then, in a new migration, i'm trying to create another table, which will reference the first one:

up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('comments', {
      id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
      title: { type: Sequelize.STRING },
      content: { type: Sequelize.TEXT },
      createdAt: { type: Sequelize.DataTypes.DATE },
      updatedAt: { type: Sequelize.DataTypes.DATE },
      articleId: {
        type: Sequelize.INTEGER,
        references: {
          model: {
            tableName: 'articles',
            schema: 'schema'
          },
          key: 'id'
        },
      }
    },
    );
  }

I get

errno: 150 "Foreign key constraint is incorrectly formed"

Tried making this association in various ways, as i saw on the internet- all with the same error. What could be the problem here? I will mention that the first table(articles) already exists in the DB.

Upvotes: 2

Views: 2734

Answers (1)

i.brod
i.brod

Reputation: 4603

Solved: It seems there is a mistake in the documentation. The way to do it is:

articleId: {
        type: Sequelize.INTEGER,
        references: {
          model:"articles",
          key:"id"
        },
      }

Upvotes: 2

Related Questions