Through model is generally used for many to many
data relation.
For example you have 3 models:
User
with id
and username
fields;
Team
with id
and teamName
fields;
TeamMember
with userId
and teamId
fields.
User
can be a member of many Team
and Team
can have many User
. And the relation of User
and Team
will be stored in TeamMember
.
To create many to many
relations in loopback you have to add relation
property to your model definition files:
- In
User
model definition file (user.json)
"relations": {
"teams": {
"type": "hasMany",
"model": "team",
"foreignKey": "userId",
"through": "teamMember"
}
}
- In
Team
model definition file
"relations": {
"users": {
"type": "hasMany",
"model": "user",
"foreignKey": "teamId",
"through": "teamMember"
}
}
- And in
TeamMember
model definition file
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"foreignKey": "userId"
},
"team": {
"type": "belongsTo",
"model": "team",
"foreignKey": "teamId"
}
}
You can also find information about "through model" on StrongLoop's docs