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

Referencing one model from another model in node.js

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

然后在 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": {}
}

根据 this documentation page(参见 "Methods added to the model for belongsTo" 部分的开头),您正在寻找 Answer.prototype.question() 方法。也许在您的示例中它需要小写?

我猜测您提供的代码来自您的 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();
    });
  });
});

请注意,如果您想在 request-response 循环的其他步骤中执行此操作,可能会有所不同。每当调用 /api/Answers/[id] 时,您都会命中此远程挂钩。

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

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

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