1

我有两个模型usersappointments.

users模型如下-

{
    "users": {
      "0": {
        "id": "1",
        "name": "test1",
        "role": "doctor"
      },
      "1": {
        "id": "2",
        "name": "test2",
        "role": "patient"
      },
      "2": {
        "id": "3",
        "name": "test3",
        "role": "support"
      }
    }
  }

现在在上面的模型中,如果角色是医生,我们称它为doctor_id,如果patient那么patient_id等等。

现在我的约会模式如下->

{
    "name": "appointments",
    "plural": "appointments",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
      "validateUpsert": true
    },
    "properties": {
      "appointmentDate": {
        "type": "date"
      },
      "appointmentTime": {
        "type": "string"
      },
      "doctorId": {
        "type": "string"
      },
      "patientId": {
        "type": "string"
      }
    },
    "validations": [],
    "relations": {
      "Doctor": {
        "type": "belongsTo",
        "model": "users",
        "foreignKey": "doctorId"
      },
      "Patient": {
        "type": "belongsTo",
        "model": "users",
        "foreignKey": "patientId"
      }
    },
    "acls": [],
    "methods": {}
  }

所以当我尝试GET所有约会时,它不会发送关系数据users。如果我添加单个关系,它会按预期工作,但不能处理来自同一模型的多个关系。

提前致谢,

4

2 回答 2

0

如果您转到 belongsTo 文档,您会看到该foreignKey字段为空,因此您需要将其从关系定义中删除。

您可能还想定义关系的另一端。

定义一个 hasMany 关系 users hasMany appointments

{
  "name": "users",
  "base": "PersistedModel",
  ...
  "relations": {
    "doctors": {
      "type": "hasMany",
      "model": "appointments",
      "foreignKey": "doctorId"
    },
    "patients": {
      "type": "hasMany",
      "model": "appointments",
      "foreignKey": "patientId"
    },
  ...
}

但是,您尝试执行的操作可能不受支持(事实上,我什至不确定这对 LoopBack 是否有意义)。

您可以查看有关多态关系的文档,即使这是一项正在进行的工作,也没有提到同时Model A hasMany Model B通过多个foreignKey关系。

LoopBack 需要有一些逻辑来在第一个外键下搜索,如果没有找到,则在另一个外键下搜索,我不确定是否支持这种复杂的组合。

建议

为什么不定义两种模型,一种用于医生,一种用于患者,而是有两种不同的关系?您甚至可以访问有关 HasManyThrough 关系的文档,并且您可以看到一个示例,该示例模拟了与您正在尝试做的事情非常相似的事情。

于 2016-11-27T15:12:30.463 回答
0

包括我之前的评论以提供上下文:

我这样做的方式,我相信外键应该是“”。您不应该定义医生 ID 和患者 ID,您可能必须在用户类中使用外键“医生”和“患者”定义两个 hasMany 关系

这里举个例子是我的用户类(称为客户)中定义的关系

"commentsWritten": {
  "type": "hasMany",
  "model": "comment",
  "foreignKey": "sourceCustomerId"
},
"commentsReceived": {
  "type": "hasMany",
  "model": "comment",
  "foreignKey": "targetCustomerId"
},

然后在我的评论定义中,我有以下内容

"properties": {
  ...
  "targetCustomerId": {
    "type": {
      "required": true
    }
  },
  "sourceCustomerId": {
    "type": {
      "required": true
    }
  }
},    
"relations": {
  "targetCustomer": {
    "type": "belongsTo",
    "model": "customer",
    "foreignKey": ""
  },
  "sourceCustomer": {
    "type": "belongsTo",
    "model": "customer",
    "foreignKey": ""
  }
},

请注意,我确实定义了属性(id),但如果我没记错的话,这只是为了让它们不为空,即你不应该需要它。

于 2016-11-04T18:48:34.370 回答