0

I wrote a nodejs app with mysql db and Sequalize as an ORM. Every things is ok. I define models and migration to create database and seeders. I want to create a product model that in this model i have two foreign keys: (categoryId & shopId).

when i was create migration files, I create shop model after product model. and this is create a problem for me. when i want to create table in database using "sequelize db:migrate" command i get this error:

ERROR: Cannot add foreign key constraint

I read this link and know this is not the reason for my problem. but how can i resolve this bug? i try to define up and down as an async function but this error did not resolve.

module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable(
  'products', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: Sequelize.INTEGER,
    },
    name: {
      type: Sequelize.STRING(255),
      allowNull: false,

    },
    description: {
      type: Sequelize.STRING(1024),
      allowNull: false,

    },
    price: {
      type: Sequelize.FLOAT,
      allowNull: false,
    },
    old_price: {
      type: Sequelize.FLOAT,
      allowNull: false,
    },
    type: {
      type: Sequelize.STRING(255),
    },
    height: {
      type: Sequelize.INTEGER,
    },
    width: {
      type: Sequelize.INTEGER,
    },
    categoryId: {
      type: Sequelize.INTEGER,
      references: {
        model: 'categories',
        key: 'id',
      },
    },
    shopId: {
      type: Sequelize.INTEGER,
      references: {
        model: 'shops',
        key: 'id',
      },
    },
    createdAt: {
      allowNull: false,
      type: Sequelize.DATE,
    },
    updatedAt: {
      allowNull: false,
      type: Sequelize.DATE,
    },
  },
),
down: (queryInterface, Sequelize) => queryInterface.dropTable('products'),
}
Fateme Ahmadi
  • 344
  • 1
  • 6
  • 18

1 Answers1

0

You're passing the model as string. You need to point to your class.

Try this:

 categoryId: {
      type: Sequelize.INTEGER,
      references: {
        model: categories,
        key: 'id',
      },
    },
William Prigol Lopes
  • 1,803
  • 14
  • 31