sailsjs-创建一个POST多个记录和关联 [英] sailsjs - one POST multiple records and associations created
问题描述
发票型号:
attributes: {
number: {
type: 'integer'
}
lines: {
collection: 'line',
via: 'invoice'
}
}
线型:
attributes: {
name: {
type: 'integer'
}
invoice: {
model: 'invoice'
}
}
如您所见,这些模型具有一对多关系.一切正常.
As you can see these models have a One-To-Many relationship. Everything is working fine.
但是现在我想使用关联的Blueprint API创建新的发票和新的行.
But now I want to create a new Invoice and new Lines with the Blueprint API that are associated.
文档说您可以使用以下模式创建新记录并将其添加到现有记录: POST/:model/:id/:association/:fk
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.
我应该为此创建一个自定义的Controller Action,还是我想得太多,应该做完全不同的事情?
Should I create a custom Controller Action for this, or am I overthinking this and I should do this whole thing completely different?
推荐答案
可以在SailsJS中使用以下代码创建带有新行的新发票:
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'
}
]})
这将创建一个编号为1的新发票,并创建一个名称为1的新行.第1行将与发票相关.由于行是一个集合,您可以将它们添加为数组,因此可以在发票中添加多个行.您可以在InvoiceController中覆盖您的create函数,然后添加此代码.
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.
另一种解决方案是使用Promises.确保使用以下命令安装bluebird:
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');
您可以使用以下代码:
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);
})
}
首先,它会创建一个编号为2的发票.如果成功,它将创建一个行,并且作为发票的参数,您将获得上一个create调用的结果.有关承诺的信息,请检查 http://bluebirdjs.com/docs/getting-started.html
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
这篇关于sailsjs-创建一个POST多个记录和关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!