【发布时间】:2018-10-04 15:42:49
【问题描述】:
我正在尝试使用父模型的 uRL 通过父模型创建相关模型
父级:应用程序 相关:申请人 这是下面的关系
applications --> hasMany --> 申请者(外键:申请 ID ) 申请人 --> BelongsTo --> 申请(外键:applicationid)
我想使用父模型的 url 对两个模型进行 upsert 补丁 /api/applications
下面是applications.js文件
module.exports = function(Application)
{
Application.afterRemote('upsert', function(ctx, instance, next){
var response ={};
response.id = ctx.result.id;
var applicants = ctx.req.body.applicants || undefined;
Application.getApp(function (err, app) {
var resp = { "applicants" :[]};
if (applicants){
for (var i=0; i<applicants.length ; i++)
{
applicants[i].application_id = ctx.result.id;
app.models.Applicants.upsert(applicants[i], function (err, result)
{
if (err) throw err;
if (!result) {
var err = new Error("Insert into Applicant failed");
err.statusCode = 500;
next(err);
}
// This prints the result in the console.
console.log('***** In APP' + JSON.stringify(result));
resp.applicants.push(result);
});
console.log(JSON.stringify(applicants));
}
// This still results in a empty array
response.applicants = resp.applicants;
ctx.result = response;
}
});
next();
});
如何将 upsert 的结果获取到申请者模型,然后在 api 的应用程序响应中将其发送回。
谢谢
【问题讨论】:
-
我并没有完全理解您想要达到的目标,但请记住您的 'app.models.Applicants.upsert(...' 运行 异步 这就是为什么 response.applicants 在你的情况下总是会导致一个空数组。
-
是否有另一种方法可以同步调用相关模型的 upsert 方法。一旦创建/修改了申请人,我想将响应发送回客户,其中包含申请详细信息和申请人详细信息示例:{“application_id”:1,“applicants”:[{“applicant_id”:1,“application_id”: 1, "name" : "abc", "country" : "IN" .......}]} 或者有没有更好的方法来处理这种要求。
标签: node.js loopbackjs