【发布时间】:2014-06-22 10:04:37
【问题描述】:
Teacher(One) 和 Children(Many) 之间存在一对多关系。
如果我这样做:
Teacher.destroy(teacherId).exec(function(err){});
子项不会自动删除。
这是一个错误还是我应该手动删除它们? 如果这不是错误,不删除孩子的解释是什么?
【问题讨论】:
标签: node.js orm sails.js waterline
Teacher(One) 和 Children(Many) 之间存在一对多关系。
如果我这样做:
Teacher.destroy(teacherId).exec(function(err){});
子项不会自动删除。
这是一个错误还是我应该手动删除它们? 如果这不是错误,不删除孩子的解释是什么?
【问题讨论】:
标签: node.js orm sails.js waterline
Waterline 目前不支持级联删除。它可能是未来版本中的一个配置选项,但它可能永远不会是默认值。在大多数生产就绪的应用程序中,您可能无论如何都应该进行软删除。无论哪种情况,您都可以使用afterDestroy lifecycle callback 获得您想要的。
在api/models/Teacher.js 中,类似:
module.exports = {
attributes: {
// attributes here
},
afterDestroy: function(destroyedRecords, cb) {
// Destroy any child whose teacher has an ID of one of the
// deleted teacher models
Child.destroy({teacher: _.pluck(destroyedRecords, 'id')}).exec(cb);
}
}
您可以使用 afterUpdate 方法对软删除执行类似的操作。
【讨论】:
one to manymany 表上的外部属性的值在销毁发生后将是NULLED,因此导致许多对象没有被销毁。我建议在 beforeDestory 生命周期中销毁子对象。