gpt4 book ai didi

node.js - 从 node.js 中的另一个模型引用一个模型

转载 作者:搜寻专家 更新时间:2023-10-31 23:53:13 26 4
gpt4 key购买 nike

我有两个模型问题和答案。一个问题有很多答案,一个答案属于一个问题。

然后在 Loopback 中提供对 Answer 的引用。我想不通的是如何获得答案所属问题的引用!?

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)。上下文仅在 remote hook 期间给出或其他此类行动。因此,我将根据通过 ID 查找 Answer 然后获取相关问题的 Hook 为您提供答案。此代码应放入您的 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] 时,您都会命中此远程 Hook 。

第二个注意:如果您只在客户端需要它,您也可以直接从 API 获取这些数据:

.../api/Answers?filter={"include":"question"}

[已更新以显示保存问题。]

关于node.js - 从 node.js 中的另一个模型引用一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com