nicholaswmin
nicholaswmin

Reputation: 23009

Loopback multiple one to many relationships

I've started getting my hands dirty with Loopback and I'm a bit confused with the model relationship declarations.

Example Model

Person

Note that idcountrybirth and idcountrynationality can reference different counties for each instance of a Person

Relationship for the above

I was looking for something along the lines of hasA for each of the 2 country fields but this kind of relationship doesn't exist.

What kind of relationships do I need to set on Person for the Countries?

Here's an example model of my current ERD, which I'm trying to rework basing it on Loopback.

screenshot of ERD diagram showing one to many relationships on 2 fields in Person table, related with Country table

Upvotes: 1

Views: 270

Answers (1)

Overdrivr
Overdrivr

Reputation: 6606

You can use a hasOne relation for each. Don't define idcountrybirth and idcountrynationality as properties, because they both represent a relation between a Person and Country.

{
  "name": "Person",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "firstname": {
      "type": "string"
    },
    "lastname": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "birthCountry": {
      "type": "hasOne",
      "model": "Country",
      "foreignKey": "birthCountryId"
    },
    "nationality": {
      "type": "hasOne",
      "model": "Country",
      "foreignKey": "nationalityCountryId"
    },
  },
  "acls": [],
  "methods": []
}

Then, using REST API

POST /api/Person
{
  "firstname": "R.",
  "lastname" : "Federer"
}

Then, assign him a birth country

POST /api/Person/1/birthCountry
{
  "name": "Switzerland"
}

And a nationality

POST /api/Person/1/nationality
{
  "name": "South Africa"
}

Some people have multiple nationalities, so you can use a hasMany relationship instead of hasOne for the nationality relationship ;)

Upvotes: 1

Related Questions