Handonam
Handonam

Reputation: 618

Save multiple models in loopback

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:

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

Upvotes: 0

Views: 1377

Answers (1)

conradj
conradj

Reputation: 2610

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

Upvotes: 3

Related Questions