How can I update hasandbelongstomany relations for multiple models at once in strongloop loopback

断了今生、忘了曾经 提交于 2019-12-07 15:22:22

问题


I have 2 models in a Strongloop Loopback API

  • Products
  • Tags

Between those 2 models I have defined a hasAndBelongsToMany-relation. In my CMS I want a bulk-update functionality for my products, in which I can select many Products, and assign many tags, in one action.

How can I save those easily to my Mysql-DB, without having to iterate over each product, then iterate over each tag, and link those 2 ?

I checked in the docs and found the add and remove functions, but those only connect one model to one relatedModel. Is there already loopback-functionality to do what I want?


回答1:


I wrote a custom (updated) function along with a helper in a service:

/*
* 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);
  });
}



回答2:


Unfortunately, there is no bulk update yet. See https://github.com/strongloop/loopback/issues/1275



来源:https://stackoverflow.com/questions/31292609/how-can-i-update-hasandbelongstomany-relations-for-multiple-models-at-once-in-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!