Reputation: 23009
I've started getting my hands dirty with Loopback and I'm a bit confused with the model relationship declarations.
Person
firstname
lastname
idcountrybirth // references country table
idcountrynationality // references country table again
Note that idcountrybirth
and idcountrynationality
can reference different counties for each instance of a Person
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.
Upvotes: 1
Views: 270
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