如何删除通过关系创建的相关项目?
How do I remove the related items created through relationship?
我有 3 个模型:ModelA、ModelB 和 ModelC。
模型 "A" 通过模型 "C" 与模型 "B" 有关系 (HasManyThrough)。
如何删除相关项目?
module.exports = function(ModelA) {
ModelA.beforeRemote('deleteById', function(context, remoteMethodOutput, next) {
//Remove relationships
next();
});
};
一些考虑:
调试上下文以实际找到随请求发送的 ID。我使用通用示例来获取模型 A 的 ID。
要删除相关的 modelB 实例,modelAInstance.modelB.destroyAll() 其中 modelB 是关系的名称,"modelA hasMany modelB".
ModelA.beforeRemote('deleteById', function(context, remoteMethodOutput, next) {
//get the id of ModelA from context object.
var id = context.req.id;
//find the model instance to delete.
ModelA.findById(id, function(err, modelAInstance) {
if (err) throw err;
//destroy all ModelB instance related to modelAInstance.
modelAInstance.modelB.destroyAll({}, function(err, info) {
if (err) throw err;
console.log(info);
});
});
next();
});
我有 3 个模型:ModelA、ModelB 和 ModelC。
模型 "A" 通过模型 "C" 与模型 "B" 有关系 (HasManyThrough)。
如何删除相关项目?
module.exports = function(ModelA) {
ModelA.beforeRemote('deleteById', function(context, remoteMethodOutput, next) {
//Remove relationships
next();
});
};
一些考虑:
调试上下文以实际找到随请求发送的 ID。我使用通用示例来获取模型 A 的 ID。
要删除相关的 modelB 实例,modelAInstance.modelB.destroyAll() 其中 modelB 是关系的名称,"modelA hasMany modelB".
ModelA.beforeRemote('deleteById', function(context, remoteMethodOutput, next) { //get the id of ModelA from context object. var id = context.req.id; //find the model instance to delete. ModelA.findById(id, function(err, modelAInstance) { if (err) throw err; //destroy all ModelB instance related to modelAInstance. modelAInstance.modelB.destroyAll({}, function(err, info) { if (err) throw err; console.log(info); }); }); next(); });