首页 > 解决方案 > Loopback 3:一个模型上的多个 HasOne 关系

问题描述

所以,我打开了她的一个问题,因为在我看来它应该像我想的那样工作......但可能是错误的,所以寻找另一种方式

所以,我几乎有两个模型,Wedding 和 Person。婚礼有这些关系集:

"people": {
  "type": "hasMany",
  "model": "person",
  "foreignKey": "",
  "options": {
    "nestRemoting": true
  }
},
"partner1": {
  "type": "hasOne",
  "model": "person",
  "foreignKey": ""
},
"partner2": {
  "type": "hasOne",
  "model": "person",
  "foreignKey": ""
}

我的一份婚礼文件看起来像这样(如果你看不出来,我正在使用 mongoDB):

{
  "_id": "5de78c76f89d1a8ad4091ca5",
  "date": "2019-12-04T10:37:42.000Z",
  "userId": "5de78c76f89d1a8ad4091ca4",
  "created": "2019-12-04T10:37:42.720Z",
  "partner1Id": "5de78c77f89d1a8ad4091ca6",
  "partner2Id": "5de78c77f89d1a8ad4091ca7"
}

因此,当我设置包含过滤器并执行以下操作时:

{ "include": ["partner1", "partner2"]}

在我的环回 API 浏览 器中http://localhost:3000/api/weddings/5de78c76f89d1a8ad4091ca5

我得到:

{
  "date": "2019-12-04T10:37:42.000Z",
  "id": "5de78c76f89d1a8ad4091ca5",
  "userId": "5de78c76f89d1a8ad4091ca4",
  "created": "2019-12-04T10:37:42.720Z",
  "partner1Id": "5de78c77f89d1a8ad4091ca6",
  "partner2Id": "5de78c77f89d1a8ad4091ca7",
  "partner1": {
    "id": "5de78c77f89d1a8ad4091ca7",
    "fullName": "Jessica Alba",
    "spouse": "spouse2",
    "contacts": [],
    "verified": false,
    "created": "2019-12-04T10:37:43.292Z",
    "updated": "2019-12-04T10:37:43.292Z",
    "userId": "5de78c76f89d1a8ad4091ca4",
    "weddingId": "5de78c76f89d1a8ad4091ca5"
  },
  "partner2": {
    "id": "5de78c77f89d1a8ad4091ca7",
    "fullName": "Jessica Alba",
    "spouse": "spouse2",
    "contacts": [],
    "verified": false,
    "created": "2019-12-04T10:37:43.292Z",
    "updated": "2019-12-04T10:37:43.292Z",
    "userId": "5de78c76f89d1a8ad4091ca4",
    "weddingId": "5de78c76f89d1a8ad4091ca5"
  }
}

但是,我期待这个:

{
  "date": "2019-12-04T10:37:42.000Z",
  "id": "5de78c76f89d1a8ad4091ca5",
  "userId": "5de78c76f89d1a8ad4091ca4",
  "created": "2019-12-04T10:37:42.720Z",
  "partner1Id": "5de78c77f89d1a8ad4091ca6",
  "partner2Id": "5de78c77f89d1a8ad4091ca7",
  "partner1": {
    "id": "5de78c77f89d1a8ad4091ca6",
    "fullName": "Michael Knight",
    "spouse": "spouse1",
    "contacts": [],
    "verified": false,
    "created": "2019-12-04T10:37:43.292Z",
    "updated": "2019-12-04T10:37:43.292Z",
    "userId": "5de78c76f89d1a8ad4091ca4",
    "weddingId": "5de78c76f89d1a8ad4091ca5"
  },
  "partner2": {
    "id": "5de78c77f89d1a8ad4091ca7",
    "fullName": "Jessica Alba",
    "spouse": "spouse2",
    "contacts": [],
    "verified": false,
    "created": "2019-12-04T10:37:43.292Z",
    "updated": "2019-12-04T10:37:43.292Z",
    "userId": "5de78c76f89d1a8ad4091ca4",
    "weddingId": "5de78c76f89d1a8ad4091ca5"
  }
}

关于为什么的任何想法?为什么我会为 partner1 和 partner2 获得相同的两条记录?

标签: loopback

解决方案


不要使用“hasOne”,而是使用“belongsTo”。


推荐阅读