Save multiple models in loopback

为君一笑 提交于 2019-12-01 12:45:31

问题


I'm doing research on loopback and was wondering if it's possible to save to multiple models from one request. Say.. an Post has many Tags with many Images. A user form would have the following:

  • Post Title
  • Post Description
  • Tag Names (A multi field. E.g.: ['Sci-Fi', 'Fiction', 'BestSeller']
  • Image File (Hoping to process the file uploaded to AWS, maybe with skipper-s3?)

How would I be able to persist on multiple models like this? Is this something you do with a hook?


回答1:


You can create RemoteMethods in a Model, which can define parameters, so in your example you could create something like this in your Post model:

// remote method, defined below
Post.SaveFull = function(title, 
        description,
        tags,
        imageUrl,
        cb) {

    var models = Post.app.Models; // provides access to your other models, like 'Tags'

    Post.create({"title": title, "description": description}, function(createdPost) {
         foreach(tag in tags) {
             // do something with models.Tags

         }
         // do something with the image

         // callback at the end
         cb(null, {}); // whatever you want to return
    })

}

Post.remoteMethod(
    'SaveFull', 
    {
      accepts: [
          {arg: 'title', type: 'string'},
          {arg: 'description', type: 'string'},
          {arg: 'tags', type: 'object'},
          {arg: 'imageUrl', type: 'string'}
        ],
      returns: {arg: 'Post', type: 'object'}
    }
);


来源:https://stackoverflow.com/questions/34340692/save-multiple-models-in-loopback

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