具有不同关系属性名称的环回中的多对多关系

时间:2018-10-06 21:56:26

标签: loopback

我有以下型号:

  • Account
  • Page
  • AccountPage

AccountPage是“直通”模型,这是我对这些模型的配置

AccountPage.json

{
  "name": "AccountPage",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "subscriptionDate": {
      "type": "date"
    }
  },
  "validations": [],
  "relations": {
    "subscriber": {
      "type": "belongsTo",
      "model": "Account",
      "foreignKey": "subscriberId"
    },
    "page": {
      "type": "belongsTo",
      "model": "Page",
      "foreignKey": "pageId"
    }
  },
  "acls": [],
  "methods": {}
}

Page.json

{
  "name": "Page",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "title": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": 
    "subscribers": {
      "type": "hasMany",
      "model": "Account",
      "foreignKey": "subscriberId",
      "through": "AccountPage",
      "keyThrough": "pageId"
    }
  },
  "acls": [],
  "methods": {}
}

Account.json

{
  "name": "Account",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {},
  "validations": [],
  "relations": {
    "pages": {
      "type": "hasMany",
      "model": "Page",
      "foreignKey": "",
      "through": "AccountPage",
      "keyThrough": "subscriberId"
    }
  },
  "acls": [],
  "methods": {}
}

当我访问GET / Pages / {id} / subscribers 时,我得到

  

“没有为AccountPage模型定义“关系\”帐户\”

如果我将"subscriber"中的AccountPage.json关系名称更改为"account"可以正常工作,这是错误还是我做错了?

1 个答案:

答案 0 :(得分:0)

我知道了,这是在foreignKeykeyThrough模型中错误地配置了PageAccountAccount模型中的Page关系的foreignKey应该具有foreigKey的pageId,如文档“指定自定义foreignKey(用于 this 模型)相关模型”,因此应为pageId而不是subscriberId

因此Page模型关系为( Page.json ):

"subscribers": {
      "type": "hasMany",
      "model": "Account",
      "foreignKey": "pageId",
      "through": "AccountPage",
      "keyThrough": "subscriberId"
    }

Account模型关系为( Account.json ):

"pages": {
      "type": "hasMany",
      "model": "Page",
      "foreignKey": "subscriberId",
      "through": "AccountPage",
      "keyThrough": "pageId"
    }

现在一切正常