的before save和after save操作的钩有一个data或instance含那将被改变的部分数据或模型实例属性。看这里。如何访问before delete挂钩中的模型实例?
即将发生的情况:删除特定模型后,我想删除相关项目。
我也使用before delete观察器实现了这一点。
在此示例中,存在一个类别模型,该模型与许多产品具有关联,并通过categoryId属性关联。
它首先根据categoryId搜索所有匹配的产品,然后循环搜索结果集products以将其逐一删除。
module.exports = function (Category) {
Category.observe('before delete', function (ctx, next) {
// It would be nice if there was a more elegant way to load this related model
var Product = ctx.Model.app.models.Product;
Product.find({
where: {
categoryId: ctx.where.id
}
}, function (err, products) {
products.forEach(function (product) {
Product.destroyById(product.id, function () {
console.log("Deleted product", product.id);
});
});
});
next();
});
};
Run Code Online (Sandbox Code Playgroud)
我试图使用destroyAll方法来实现它,但这并没有给我预期的结果。
上面的代码对我有用,但是看起来可以增强很多。