When defining relation using "slc loopback:relation", it prompts about "through model" at the last line.
? Select the model to create the relationship from: CoffeeShop
? Relation type: has many
? Choose a model to create a relationship with: Reviewer
? Enter the property name for the relation: reviewers
? Optionally enter a custom foreign key:
? Require a through model? No
Could someone briefly explain what a through model is? Some example will be greatly appreciated.
A LoopBack model is a JavaScript object with both Node and REST APIs that represents data in backend systems such as databases. Models are connected to backend systems via data sources. You use the model APIs to interact with the data source to which it is attached.
PersistedModel is the base class for models connected to persistent data sources such as databases and is also the base class for all built-in models (except Email). It provides all the standard create, read, update, and delete (CRUD) operations and exposes REST endpoints for them.
A remote method is a method of a model, exposed over a custom REST endpoint. Use a remote method to perform operations not provided by LoopBack's standard model REST API. Note: The easiest way to define a remote method is by using the command-line remote method generator.
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:
User model definition file (user.json)"relations": {
"teams": {
"type": "hasMany",
"model": "team",
"foreignKey": "userId",
"through": "teamMember"
}
}
Team model definition file"relations": {
"users": {
"type": "hasMany",
"model": "user",
"foreignKey": "teamId",
"through": "teamMember"
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With