在环回中包含相关模型中的子模型

时间:2015-09-15 19:42:58

标签: node.js loopbackjs

我有帐户模型,其中有多个帖子,帖子属于帐户

帐户:

{
  "name": "Account",
  "base": "User",
  "relations": {
    "post": {
      "type": "hasMany",
      "model": "Post",
      "foreignKey": "accountId"
    },
...
  },
...
}

发表:

    {
      "name": "Post",
      "base": "PersistedModel",
      "relations": {
        "account": {
          "type": "belongsTo",
          "model": "Account",
          "foreignKey": ""
        }
      },
      ...
    }

现在,我有模型问题,它是Post模型的子模型。

{
  "name": "Question",
  "base": "Post", ...
}

我想查询特定帐户的所有字段,并将所有问题都包含在此类

Account.findById({
        id: id,
        filter: {include: 'question'},
function(){...});

有可能吗?

1 个答案:

答案 0 :(得分:1)

Account.findById(id, { include: { relation: 'questions' } }, function(){...});

您可能需要在questions模型中创建Account关系,因为我认为它不会继承Post模型中的关系。

另请注意,您应该将post关系重命名为posts。所以你的关系部分应该是这样的:

Account:
{
  "name": "Account",
  "base": "User",
  "relations": {
    "posts": {
      "type": "hasMany",
      "model": "Post",
      "foreignKey": "accountId"
    },
    "questions": {
      "type": "hasMany",
      "model": "Question",
      "foreignKey": "accountId"
    }
...
  },
...
}
相关问题