Home > Blockchain >  Cannot add foreign key constraint - SEQUELIZE
Cannot add foreign key constraint - SEQUELIZE

Time:09-22

I thought an error like this was supposed to associated with field type(data type) mismatch. but this has proven to be false as i have tried changing datatypes on the table id and the foreign key to integer and uuid but still it the same result. I would like to also point out that am totally new to nodejs so you know where am coming from...

migration/xxxxxxx-demo-user.js

'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
        primaryKey: true
      },
      firstName: {
        type: Sequelize.STRING
      },
      lastName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      phoneNumber: {
        type: Sequelize.STRING
      },
      country: {
        type: Sequelize.STRING
      },
      PlanId: {
        type: Sequelize.UUID,
        references: {
            model: 'Plans',
            key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      password: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  }
};

migrations/xxxxxx-demo-plan.js

'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Plans', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
        primaryKey: true
      },
      title: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Plans');
  }
};

Error Message

enter image description here

CodePudding user response:

Try to rename your "xxxxxxx-demo-user.js" and "xxxxxxx-demo-plan.js" migration file names. As at first you've run users migrations before plan migration, so that's why your "planId" field (of users table) pointing to non-existing plans table. Try something like this, and run migrations again:

20210918101111-demo-plan.js
20210918102222-demo-user.js
sequelize db:migrate:undo:all
sequelize db:migrate
  • Related