【问题标题】:Remove cascade onDelete constraint from table using sequelize使用 sequelize 从表中删除级联 onDelete 约束
【发布时间】:2021-03-11 08:16:04
【问题描述】:

我有一个位置和设备表。设备表有位置 ID,这就是模型的样子

 module.exports = (sequelize, DataTypes) => {
  const devices = sequelize.define('devices', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    location_id: {
      type: DataTypes.UUID,
      allowNull: true,
      onDelete: 'CASCADE',
      references: {
        model: 'locations',
        key: 'id',
      },
    },
    model: {
      allowNull: true,
      type: DataTypes.STRING,
    },
  
    created_at: {
      allowNull: false,
      type: DataTypes.DATE,
    },
    updated_at: {
      allowNull: false,
      type: DataTypes.DATE,
    },
  }, {});
  devices.associate = function (models) {
    devices.belongsTo(models.companies, { foreignKey: 'company_id' });
    devices.belongsTo(models.locations, { as: 'locations', foreignKey: 'location_id' });
  };
  return devices;
};

迁移如下所示

module.exports = {
  up: (queryInterface, Sequelize) => queryInterface.createTable('devices', {
    id: {
          allowNull: false,
          primaryKey: true,
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
        },
        location_id: {
          type: DataTypes.UUID,
          allowNull: true,
          onDelete: 'CASCADE',
          references: {
            model: 'locations',
            key: 'id',
          },
        },
        model: {
          allowNull: true,
          type: DataTypes.STRING,
        },
      
        created_at: {
          allowNull: false,
          type: DataTypes.DATE,
        },
        updated_at: {
          allowNull: false,
          type: DataTypes.DATE,
        },
  }),
  down: (queryInterface) => queryInterface.dropTable('devices'),
};

以上导致设备连同位置一起被删除。

这已经迁移了。

现在我需要删除 onDelete 级联,以便删除位置不会导致设备被删除。

如何编写迁移以删除 onDelete 级联?

【问题讨论】:

    标签: sequelize.js cascade


    【解决方案1】:
    
    'use strict';
    
    module.exports = {
        up: async (queryInterface, DataTypes) => {
            await queryInterface.changeColumn('devices', 'location_id', {
                type: DataTypes.UUID,
                allowNull: true,
                // onDelete: 'CASCADE',  <-    Remove this line
                references: {
                    model: 'locations',
                    key: 'id',
                },
            });
        },
    
        down: async (queryInterface, Sequelize) => {
        }
    };
    
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多