我有两个模型问答。一个问题有很多答案,一个答案属于一个问题。
然后在“回送”中提供对答案的引用。我不知道的是,然后如何获得答案所属的问题的参考!?
module.exports = function(Answer) {
console.log(ctx.instance.question)
console.log(ctx.instance.question.points) // undefined
};
我可以得到看起来像是对该对象的引用……但是我不知道如何引用该对象的任何属性!
如何引用属于另一个模型的模型?
以下提供的问题和答案供参考。
{
"name": "Question",
"plural": "Questions",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"text": {
"type": "string",
"required": true
},
"points": {
"type": "number",
"required": true
}
},
"validations": [],
"relations": {
"answers": {
"type": "hasMany",
"model": "Answer",
"foreignKey": ""
},
"approval": {
"type": "hasOne",
"model": "Approval",
"foreignKey": ""
},
"student": {
"type": "belongsTo",
"model": "Student",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
{
"name": "Answer",
"plural": "Answers",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"text": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"question": {
"type": "belongsTo",
"model": "Question",
"foreignKey": ""
},
"student": {
"type": "belongsTo",
"model": "Student",
"foreignKey": ""
},
"approval": {
"type": "belongsTo",
"model": "Approval",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
我猜您提供的代码是common/model/answer.js
基于文件的外观而来的,但是该文件是在应用程序设置期间执行的。上下文(ctx
在您的示例中)将不存在。仅在远程挂接或其他此类操作期间提供上下文。因此,我将根据钩子为您提供答案,以根据Answer
其ID查找,然后获取相关问题。此代码应放在您的common/model/answer.js
文件中(在导出的包装函数中):
Answer.afterRemote('findById', function(ctx, theAnswer, next) {
theAnswer.question(function(err, question) { // this is an async DB call
if (err) { return next(err); } // this would be bad...
console.log(question);
// You can then alter the question if necessary...
question.viewCount++
question.save(function(err) {
if (err) {
// an error here might be bad... maybe handle it better...
return next(err);
}
// if get here things are good, so call next() to move on.
next();
});
});
});
请注意,如果您想在请求-响应周期的其他步骤中执行此操作,则可能会有所不同。每当您打到电话时,您都将打这个远程挂机/api/Answers/[id]
。
第二个注意事项:如果只需要客户端,也可以直接从API获取此数据:
.../api/Answers?filter={"include":"question"}
[已更新为显示保存问题。]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句