What does "through model" mean in loopback?
Asked Answered
N

1

15

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.

Nirvana answered 2/8, 2015 at 14:49 Comment(0)
T
17

Through model is generally used for many to many data relation. For example you have 3 models:

  1. User with id and username fields;
  2. Team with id and teamName fields;
  3. 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:

  1. In User model definition file (user.json)

"relations": {
  "teams": {
    "type": "hasMany",
    "model": "team",
    "foreignKey": "userId",
    "through": "teamMember"
  }
}
  1. In Team model definition file

"relations": {
  "users": {
    "type": "hasMany",
    "model": "user",
    "foreignKey": "teamId",
    "through": "teamMember"
  }
}
  1. 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

Thoroughgoing answered 3/8, 2015 at 13:21 Comment(2)
any idea how to add data in TeamMember model, through loopback explorer?Nickienicklaus
Explanation on Loopback documentation: loopback.io/doc/en/lb3/HasManyThrough-relations.htmlHeaviness

© 2022 - 2024 — McMap. All rights reserved.