如何在Strongloop环回中一次更新多个模型的hasandbelongstoman关系 [英] How can I update hasandbelongstomany relations for multiple models at once in strongloop loopback

查看:100
本文介绍了如何在Strongloop环回中一次更新多个模型的hasandbelongstoman关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Strongloop Loopback API中有2个模型

I have 2 models in a Strongloop Loopback API

  • 产品
  • 标签

在这两个模型之间,我定义了 hasAndBelongsToMany-relation . 在我的CMS中,我想要对产品进行批量更新功能,在一次操作中,我可以选择许多产品并分配许多标签.

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.

我如何才能轻松地将它们保存到Mysql-DB中,而不必遍历每个产品,然后遍历每个标记并链接这2个?

我检查了文档,发现添加和删除功能,但是这些功能仅将一个模型连接到一个relatedModel上.是否已经具有回送功能来执行我想要的工作?

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?

推荐答案

我在服务中编写了一个自定义(更新的)函数以及一个助手:

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

这篇关于如何在Strongloop环回中一次更新多个模型的hasandbelongstoman关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆