我在Strongloop Loopback API中有2个模型
在这两个模型之间我定义了一个 hasAndBelongsToMany-relation 。 在我的CMS中,我想要为我的产品提供批量更新功能,我可以在一个操作中选择许多产品,并分配许多标签。
如何轻松地将这些内容保存到我的Mysql-DB中,而不必遍历每个产品,然后遍历每个标记,并链接那些2?
我检查了文档并找到了添加和删除功能,但那些只将一个模型连接到一个relatedModel。是否已经有环回功能来做我想做的事情?
答案 0 :(得分:0)
不幸的是,还没有批量更新。见https://github.com/strongloop/loopback/issues/1275
答案 1 :(得分:0)
我在服务中写了一个自定义(更新)函数和一个帮助器:
/*
* Add multiple objects to a relationship
* @param {object} origin The object which hold the items
* @param {array} data The new list to be inserted
* @param {string} relation name of the relationship, for instance 'cats'
*/
exports.updateManyRelations = function(origin, data, relation){
//Destroy all old connections
return origin[relation].destroyAll().then(function(response){
//All were deleted and nothing to add
if(!data || data.length == 0){return [];}
//We have a list to go through, do the dirty work!
return addMultipleRelationsToObject(origin[relation], data, []);
}).then(function(newList){
// new items created
return newList
}, function(error){
console.log(error);
});
}
/*
* Helper function to add multiple related objects to a object in a correct promise chain
*/
var addMultipleRelationsToObject = function(objectRelation, list, newList){
if(list && list.length == 0){return Promise.resolve(newList);}
var item = list.pop();
if(!objectRelation.hasOwnProperty("add")){
return Promise.reject("Relationship is wrong for: " + objectRelation);
}
return objectRelation.add(item.id).then(function(newlyAdded){
newList.push(item);
return addMultipleRelationsToObject(objectRelation, list, newList);
});
}