如何解决使用 sequelize 从表中删除级联 onDelete 约束
我有一个位置和设备表。设备表有位置 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,{});
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,location_id: {
type: DataTypes.UUID,references: {
model: 'locations',model: {
allowNull: true,created_at: {
allowNull: false,updated_at: {
allowNull: false,}),down: (queryInterface) => queryInterface.dropTable('devices'),};
以上导致设备与位置一起被删除。
这已经迁移了。
现在我需要删除 onDelete 级联,以便删除位置不会导致设备被删除。
如何编写一个迁移来删除 onDelete 级联?
解决方法
'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) => {
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。