我有一个位置和设备表。设备表有位置 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 级联?
答案 0 :(得分:0)
'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) => {
}
};