0

I'm new to nodejs. I have created a template with expressJs. For migration and ORM purposes I am using squelizeJs with mysql2 plugin. I have created migrations and models for my tables. But I could not change the default behavior when creating foreign keys, which is to change the values of onUpdate and onDelete

How can I implement this SQL query inside sequelize migration?

CONSTRAINT `fk_keywords_2`
    FOREIGN KEY (`bot_id`)
    REFERENCES `mydb`.`bots` (`id`)
    ON DELETE RESTRICT
    ON UPDATE NO ACTION)

I have tried

'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Keywords', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER.UNSIGNED
      },
      bot_id: {
        allowNull: false,
        type: Sequelize.INTEGER.UNSIGNED,
        references: {
          model: 'Bots',
          key: 'id'
        },
        onUpdate: 'NO ACTION',
        onDelete: 'RESTRICT'
      },
      parent_id: {
        type: Sequelize.INTEGER.UNSIGNED
      },
      keyword: {
        allowNull: false,
        type: Sequelize.STRING
      },
      time_duration: {
        type: Sequelize.STRING
      },
      is_all_message_config: {
        allowNull: false,
        type: Sequelize.BOOLEAN,
        defaultValue: 0
      },
      is_catch_all_config: {
        allowNull: false,
        type: Sequelize.BOOLEAN,
        defaultValue: 0
      },
      blockedAt: {
        type: Sequelize.DATE
      },
      deletedAt: {
        type: Sequelize.DATE
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    }, {
      uniqueKeys: {
        keyword_unique_for_bot_and_parent: {
          customIndex: true,
          fields: ['bot_id', 'parent_id', 'keyword', 'deletedAt']
        }
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Keywords');
  }
};

It creates a foreign key but, both onUpdate and onDelete are set to RESTRICT

I went through their documentation but could not find something that works.

1 Answers1

0

You should try to add that action in your Keywords model file where we can define association.

static associate(models) {
    // define association here
    Keywords.hasMany(models.Bots, {
        foreignKey: 'id',
        onUpdate: 'RESTRICT',
        onDelete: 'RESTRICT'
    });
};

Thanks

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
aum trivedi
  • 129
  • 4