Search code examples
javascriptnode.jsloopbackjsstrongloop

Loopback hasOne and hasMany of the same model


I try to make a family tree. I have the model familyMember which should have two relations to it self. First is spouse and second is children. Now I tried it with:

"relations": {
  "spouse": {
    "type": "hasOne",
    "model": "familyMember",
    "foreignKey": "familyMemberId"
  },
  "children": {
    "type": "hasMany",
    "model": "familyMember",
    "foreignKey": "familyMemberId"
  }
}

But when I create a children and after a spouse it returns:

{
  "error": {
    "name": "Error",
    "status": 500,
    "message": "HasOne relation cannot create more than one instance of familyMember"
  }
}

When I request the spouse it returns the children I've made before.

How can I solve this problem?


Solution

  • From what I understand from your question you have one model familyMembers and you are refering to the property children and spouse of the same model as relation hasMany and hasOne respectively.

    Its not the best way to achieve what you are trying to get through loopback. And it has potential for error.

    The best way to do is first create a model FamilyMember through loopback.

    Then create two different models children and spouse and other related members models by inheriting the base familyMember model.

    And then add relation between these models easily.

    For more info read. Extending a model in loopback