【问题标题】:Sequelize. How to set OnUpdate to NO ACTION when creating a foreign key with migration续集。使用迁移创建外键时如何将 OnUpdate 设置为 NO ACTION
【发布时间】:2021-04-19 08:19:03
【问题描述】:

我是 nodejs 的新手。我用 expressJs 创建了一个模板。出于迁移和 ORM 的目的,我将 squelizeJs 与 mysql2 插件一起使用。我为我的表创建了迁移和模型。但是我无法更改创建外键时的默认行为,即更改onUpdateonDelete 的值

如何在 sequelize 迁移中实现这个 SQL 查询?

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

我试过了

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

它创建了一个外键,但是 onUpdateonDelete 都设置为 RESTRICT

我浏览了他们的文档,但找不到有用的东西。

【问题讨论】:

    标签: node.js sequelize.js sequelize-cli


    【解决方案1】:

    您应该尝试在 Keywords 模型文件中添加该操作,我们可以在其中定义关联。

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

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-27
      • 2018-05-16
      • 2018-06-19
      • 2015-09-16
      • 2020-10-23
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多