我正在尝试使用父模型的uRL通过父模型创建相关模型
父母:申请 相关:申请人 这是下面的关系
应用程序-> hasMany->申请人(外键:应用程序 ID ) 申请人->属于->应用程序(外键:applicationid)
我想同时使用父模型的URL对这两个模型进行升级 修补程序/ 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的应用程序响应中。
谢谢
答案 0 :(得分:0)
这就是我要做的。当然可以考虑一种更好的方法,但这可能是一个好的开始。
'use strict';
var app = require('../../server/server');
var models = app.models;
var Applicants;
app.on('started', function () {
Applicants = models.Applicants;
});
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;
if (applicants) {
var resp = {"applicants": []};
var count = 0;
for (var i = 0, applicantsLength = applicants.length; i < applicantsLength; i++) {
applicants[i].application_id = ctx.result.id;
Applicants.upsert(applicants[i], function (err, result) {
if (err)
return next(err);
if (!result) {
var err = new Error("Insert into Applicant failed");
err.statusCode = 500;
return next(err);
}
resp.applicants.push(result);
count++;
if (count === applicantsLength) {
response.applicants = resp.applicants;
ctx.result = response;
next();
}
});
}
} else {
next();
}
});
};
如果这不起作用,则应查找'before save'钩子。