我在Strongloop环回API中有2个模型
- 产品
- 标记
我如何轻松地将这些保存到我的Mysql-DB,而不必遍历每个产品,然后遍历每个标签,并链接这两个?
我检查了文档,发现了添加和删除功能,但这些功能只将一个模型连接到一个relatedModel。是否已经有环回功能来做我想要的?
我在一个服务中编写了一个自定义(更新)函数和一个helper:
/*
* 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);
});
}
遗憾的是,还没有批量更新。见https://github.com/strongloop/loopback/issues/1275