> For the complete documentation index, see [llms.txt](https://softstack-factory.gitbook.io/mean-stack/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://softstack-factory.gitbook.io/mean-stack/backend/wk8-final-project-relations/relations.md).

# Relations

Relations allow us to have one model be related another model.

### Before you start

We will be altering how the **`Favorite`** model works with our backend in this gitbook notebook.&#x20;

Originally we made the **`Favorite`** model without attaching it to an user of the angular application aka the **`AppUser`** model. We also added an entry to the favorites collection in our database to see if we could store something on your database.&#x20;

{% hint style="warning" %}
We will need to delete any **`Favorite`** entries in our database before we implement the below steps of making the **`Favorite`** model be related to the **`AppUser`**&#x4D;odel.
{% endhint %}

&#x20;We need to do this because we are altering the way these two models will work together, otherwise you'd have some inconsistent data in your database. Some **`Favorite`** model entries will be related to **`AppUser`** and some will not.

### **Summary/Overview**

{% hint style="info" %}
**Relations allow us to have one model be related another model.**&#x20;
{% endhint %}

For example:&#x20;

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQzmwjI1SKnmMNfciO%2F-LwR1ye4kZ8K7QEi7BCn%2Fimage.png?alt=media\&token=33fb9b14-1ec4-4278-be6d-e3777d52d084)

The illustration above represents a **`Customer`**  model having potentially many **`Order`** model entries, this illustrates the **"**&#x72;elatio&#x6E;**"**.

[Example reference ](https://loopback.io/doc/en/lb3/HasMany-relations.html)

Another Example:

An **`AppUser`** can have many **`Favorites` .**  This will allow us to retrieve information related to a user, more specifically what **`Favorite`** model entries a particular **AppUser** has stored in the database

{% tabs %}
{% tab title="AppUser Model Entry" %}

```typescript
appUser = {
  id: "3afsdjk212gl3af"
  firstName: "Jane",
  lastName: "Doe",
  email: "JaneDoe@mail.com"
}
```

In the above example the **id** from the **`AppUser`** model entry **(line 2)** is inserted as a “**foreign key**” on the **`Favorite`** model entry **(line 3)** on the **`Favorite`** *Model Entry Tab*.
{% endtab %}

{% tab title="Favorite Model Entry" %}

```typescript
favorite = {
    id: "5dfac7c7f809983c88298247"
    userId: "3afsdjk212gl3af"
    movieTitle: "Star Wars",
    thirdPartyMovieId: 11,
    posterPath: "/btTdmkgIvOi0FFip1sPuZI2oQG6.jpg" 
}
```

**Line 3: `Favorite`** entry's `userId` value  "**3afsdjk212gl3af**" is from the **`appUser`** entry
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
In loopback each instance will have a unique id generated for it automatically on created unless otherwise specified.
{% endhint %}

## **Relation Setup**

#### **Step 1**

In your terminal type:  **`lb relation`**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQoYOjIgKxQsk9TsmG%2Fimage.png?alt=media\&token=14bef749-55e9-4076-8889-cb416e92d65a)

#### **Step 2**

Now Select **`appUser`** as the model we are starting this relation from.

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQpZpad8JRHgEzThxy%2Fimage.png?alt=media\&token=dd08561e-731d-4632-8c1a-b9864138cd17)

#### **Step 3**

Now we will select the type of relation. In our case an **`appUser`** can have many **favorites**. So we select hasMany

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQp1x0iYQca9qBfRoV%2Fimage.png?alt=media\&token=42f12702-7793-4126-8503-da416702a286)

#### **Step 4**

Now we have the choice of the other model we want to have the relation with.  In this case **`favorite`** is model that an **`appUser`** can have many of.

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQq5jN9z9Q0XAknFfV%2Fimage.png?alt=media\&token=72226c14-d0f1-4967-a5d6-102ed8f7d577)

#### **Step 5**

Now we need a property name for the relation, favorites. This is property that will show up in our model that is the owner for example. In this case our **`appUser`** has many **`favorites`**.

The name in the parentheses( )  below is the default name of the relation unless you type in another name.

Press **`Enter`**

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQqf8rileCmHoCvRsI%2Fimage.png?alt=media\&token=dfac5042-9755-4eb5-a1a2-5cf8ee2c3d51)

#### **Step 6**

Now we enter a foreign key this will be the field added to the **`favorite`** model. In the example below **`userId`** is the foreign key that refers to the id of the **`appUser`** who it is related to.

| <p><strong>favorite = {</strong><br>    <strong>id: "5dfac7c7f809983c88298247"</strong></p><p>    <strong>userId: "3afsdjk212gl3af"</strong></p><p>    <strong>movieTitle: "Star Wars",</strong></p><p>    <strong>thirdPartyMovieId: 11,</strong></p><p>    <strong>posterPath: "/btTdmkgIvOi0FFip1sPuZI2oQG6.jpg"</strong> <br><strong>}</strong></p> |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

`UserId`above will be the foreign key.

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQrBmdT34i_uCVagFS%2Fimage.png?alt=media\&token=2201de1c-57f4-4e58-8ced-da23b397fe93)

**Step 7**\
\
Require a through model would be the case of a lets say we have a doctor and a patient they would both own the appointment. The appointment would be the through model.\
We will be selecting no.

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQnsVwCS1S-S2RvuuH%2F-LwQrk7GSYPOk2BDX_rr%2Fimage.png?alt=media\&token=f469dd38-6d0c-4d34-a062-fa5f7808c3fa)

## **Relation Recap**

We set up a “has many” relation from the **`appUser`** model to **`Favorites`** because an **`appUser`** can own many favorites . After creating this relation the **`appUser`** model will have a new property called `favorites`, and a foreign key or `userId` property will be added to the **`favorite`** model instance which will point to the unique **`id`** of the **`appUser`**.

## **Relations in Loopback Explorer**

Now restart your backend to update the new changes and go to the explorer.\
Select the **`appUser`** endpoint

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQuiQHv35k6dFIP-85%2F-LwQv-4rJQanRuCD8NRc%2Fimage.png?alt=media\&token=a08b670e-f49d-4a0e-b130-c458a885f53b)

Then scroll down and you should have new routes that will have do to with the created relation. In our case **favorites**.  Below are a list of pre-built routes that take advantage of the relation we created.

![](https://3729111192-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LJF8uz6T7DhCLClK6jV%2F-LwQuiQHv35k6dFIP-85%2F-LwQvN_KTYaI8Gz_AVpj%2Fimage.png?alt=media\&token=4890c45d-5c8a-4231-a241-af7c8e1aca91)

After you setup the token authentication and access control settings, you can use the token stored in our sessionStorage object to make a http call in angular to submit a new **`Favorite`** model entry for a particular **`appUser`** to the database.&#x20;

{% code title="main.component.ts" %}

```typescript
AddToFavorites(){
  let token = sessionStorage.getItem("token")
  let favoritesUrl = "http://localhost:3000/api/appUsers/${sessionStorage.getItem("userId")}/favorites/?access_token=${token}`"

   this._http.get( favoritesUrl )
   .subscribe(
     res => console.log("res", res)
   )
 }
```

{% endcode %}
