我使用 Pet / User example from the documentation 和sails 0.11 做了一些测试。
在Pet 模型中编写此生命周期回调会删除与pet 关联的所有users在删除它之前。
// models/Pet.js
module.exports = {
attributes: {
name:'string',
color:'string',
owners: {
collection: 'user',
via: 'pets'
}
},
beforeDestroy: function(criteria, cb) {
// Destroy any user associated to a deleted pet
Pet.find(criteria).populate('owners').exec(function (err, pets){
if (err) return cb(err);
pets.forEach(function(recordToDestroy) {
User.destroy({id: _.pluck(recordToDestroy.owners, 'id')}).exec(function(err) {
console.log('The users associated to the pet ' + recordToDestroy.name + ' have been deleted');
});
});
cb();
})
}
};
我无法在 afterDestroy 生命周期回调中执行此操作,因为那里缺少已删除记录的多对多属性。
Waterline 正在自动删除联结表的记录。
这个功能的问题是,如果一些宠物共享一些主人,它可能会删除太多东西。按照文档的示例,如果您删除宠物 Rainbow Dash,您将删除用户 Mike、Cody 和 Gabe,宠物 Pinkie Pie 和 Applejack 将是孤儿。
如果你定义了一个像这样的多对多关系,但你知道宠物不能有任何共同的所有者,那么它就可以正常工作。否则,您应该添加一个测试以检查您不会让另一只宠物成为孤儿。