Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

sequelize.js - Remove cascade onDelete constraint from table using sequelize

I have a locations and devices table . Devices table have location id and this is how the model looks like

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

Migration looks like below

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

The above causes device to be deleted along with location .

This is already migrated.

Now I have a requirement to remove onDelete cascade so that delete of location won't result in device getting deleted .

How to write a migration to drop onDelete cascade?

question from:https://stackoverflow.com/questions/65884172/remove-cascade-ondelete-constraint-from-table-using-sequelize

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...