简体   繁体   中英

sailsjs - one POST multiple records and associations created

Invoice-Model:

attributes: {
  number: {
    type: 'integer'
  }
  lines: {
    collection: 'line',
    via: 'invoice'
  }
}

Line-Model:

attributes: {
  name: {
    type: 'integer'
  }
  invoice: {
    model: 'invoice'
  }
}

As you can see these models have a One-To-Many relationship. Everything is working fine.

But now I want to create a new Invoice and new Lines with the Blueprint API that are associated.

The documentation says you can create a new record and add it to an existing one with this schema: POST /:model/:id/:association/:fk

But it does not state if it is possible to create two records at the same time and associate them.

More details: I've got an invoice and in this invoice you can add lines with products, their quantity and other stuff. Now when the user clicks on save, I need to create a new invoice and the new lines and associate them somehow.

Should I create a custom Controller Action for this, or am I overthinking this and I should do this whole thing completely different?

To create a new invoice with new lines is possible to do in SailsJS with the following code:

Invoice.create({number: 1, lines: [
  {
    name: '1'
  }
]})

This will create a new invoice with number 1 and also creates a new line with the name 1. Line 1 will be related with invoice. Since lines is an collection you can add them as a array, so this makes it possible to add more than one Line to your Invoice. You can overwrite your create function in the InvoiceController and add this code.

An alternative solution is using Promises. Make sure you install bluebird by using the command:

npm install bluebird

Put the following code in the top of your controller

var Promise = require('bluebird');

You can use the following code:

createWithPromises: function(req, res){
var lineName = 1;
var invoiceNumber = 2;

Invoice.create({number: invoiceNumber})
  .then(function(result){
    Line.create({name: lineName, invoice: result})
  })
  .then(function(result){
    sails.log(result);
  })

}

First it creates an Invoice with number 2. If succeed it will create a Line, and as parameter for invoice, you give the result from your previous create call. For information about Promises check http://bluebirdjs.com/docs/getting-started.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM