我试图通过sequelize中的3个关联表级联删除数据。
用户型号:
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var Users = sequelize.define('Users', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updatedAt: DataTypes.DATE
}, {
classMethods: {
associate: function(models) {
Users.belongsToMany(models.Books, {
through: {
model: models.History
},
foreignKey: 'userId',
onDelete: 'cascade'
});
}
}
});
return Users;
};

书籍模型:
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var Books = sequelize.define('Books', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updatedAt: DataTypes.DATE
}, {
classMethods: {
associate: function(models) {
Books.belongsToMany(models.Users, {
through: {
model: models.History
},
foreignKey: 'bookId',
onDelete: 'cascade'
});
}
}
});
return Books;
};

历史模型:
var Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
var History = sequelize.define('History', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
bookId: {
type: DataTypes.INTEGER,
allowNull: false
},
from: {
type: DataTypes.DATE,
allowNull: false
},
to: {
type: DataTypes.DATE,
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updatedAt: DataTypes.DATE
});
return History;
};

当我尝试从历史记录表中级联删除Users对象和有关该用户历史记录的所有数据时,我遇到以下错误:
更新或删除表格"用户"违反外键约束" History_userId_fkey"在桌子上"历史"
当我尝试从书籍中做同样的事情时,我遇到了以下错误:
更新或删除表格"用户"违反外键约束" History_bookId_fkey"在桌子上"历史"
如果我不想发生该错误,我首先从历史记录中删除行,然后我可以删除有关用户/书籍的行。
如何解决这个问题?
提前致谢。