我有两个偏执表(用户和电子邮件)之间的关系,我有onDelete:' cascade'关系的选项(Email.belongsTo(User,onDelete:' cascade'))。
问题在于,当我删除用户时,他的电子邮件不被级联删除。
我犯了错误或者有续集的错误吗?
我在 postgres 数据库中使用 sequelize 2.0.0-rc2 。
感谢。
PS:请看一下我用于测试的代码:
var Sequelize = require('sequelize')
, sequelize = new Sequelize('test', 'test', 'test', {dialect: 'postgres'});
var User = sequelize.define('User', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
}, {paranoid: true}); //Without paranoid the code works fine
var Email = sequelize.define('Email', {
email: Sequelize.STRING,
primary: Sequelize.BOOLEAN
}, {paranoid: true}); //Without paranoid the code works fine
Email.belongsTo(User, {onDelete: 'cascade'});
sequelize.sync().success(function () {
var userCreatedInstance = null;
var deletedUserId = null;
var cascadeDeletedEmailId = null;
User
.create({
username: 'user1',
birthday: new Date(1986, 06, 28)
})
.then(function (_user) {
userCreatedInstance = _user;
deletedUserId = userCreatedInstance.id;
return Email.create({email: 'email1@test.com', primary: true, UserId: userCreatedInstance.id});
})
.then(function (createdEmail) {
cascadeDeletedEmailId = createdEmail.id;
return userCreatedInstance.destroy();
})
.then(function () {
return User.find(deletedUserId);
})
.then(function (foundUser) {
if(foundUser){
throw new Error("Shouldn't find the user with this id");
}
return Email.find(cascadeDeletedEmailId);
})
.then(function (foundEmail){
if(foundEmail){
console.log(foundEmail.values);
throw new Error("Shouldn't find the email with this id");
}
});
});
答案 0 :(得分:1)
如果您希望级联在偏执状态下工作,则必须使用钩子。 请在下面找到我的工作方式
我在父表(关系的基础)上添加了afterDestroy钩子, 我让它得到与关联的模型,并在其上调用了destroy方法。 那样简单! 我相信我们可以使它以这种方式工作,直到维护者给我们另一种方法
// User Model
const User = sequelize.define('users', {....},
{
tableName: 'users',
deletedAt: 'deletedAt',
paranoid: true,
timestamps: true,
hooks: {
afterDestroy: function (instance, options) {
instance.getProduct().then(product=> product.destroy()); // Softdelete on product table
console.log('after destroy: destroyed');
}
}
}
);
// Product Model
const Product = sequelize.define('products', {....},
{
tableName: 'products',
deletedAt: 'deletedAt',
paranoid: true,
timestamps: true,
}
)
// User relationship with product
User.hasOne(Product,
{
as: 'Product',
onDelete: 'CASCADE',
hooks: true,
foreignKey: "userID"
})
Product.belongsTo(User, {
as: 'User',
foreignKey: "userID"
});
答案 1 :(得分:0)
我发现cascade选项只设置数据库级联选项。 sequelize没有进行级联删除。
但是,续集团队将来会为偏执桌上的级联工作。
这是一个未解决的问题:https://github.com/sequelize/sequelize/issues/2586