我有两个模型问答。一个问题有很多答案,答案属于一个问题。
然后在Loopback中提供对答案的引用。我无法弄清楚的是,我如何得到答案所属的问题的参考!?
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": {}
}
答案 0 :(得分:2)
我猜测您提供的代码来自您的common/model/answer.js
文件,基于它的外观,但该文件是在应用程序设置期间执行的。上下文(样本中的ctx
)不存在。上下文仅在remote hook或其他此类操作期间提供。因此,我将基于一个钩子给你一个答案,用于通过其ID找到Answer
,然后获得相关问题。此代码应放在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]
时,您都会点击此远程挂钩。
Seconde注意:如果您只是在客户端上需要它,您也可以直接从API获取此数据:
.../api/Answers?filter={"include":"question"}
[已更新以显示保存问题。]
答案 1 :(得分:0)
根据this documentation page(参见&#34的最开始;添加到belongsTo&#34的模型的方法;部分),您正在寻找Answer.prototype.question()方法。也许你的样本中需要小写?