3

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?

Ernie
  • 972
  • 1
  • 10
  • 23

2 Answers2

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);
  });
}
Undrium
  • 2,558
  • 1
  • 16
  • 24
0

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

superkhau
  • 2,781
  • 18
  • 9