Jakša Mališić
Jakša Mališić

Reputation: 445

How to nested include through models relationships LOOPBACK?

Lets continue with the Patient - Physician analogy from the Loopback Docs. Let's make the assumption that Physician model looks like this:

{
   "id": "4654654654654654654",
   "name": "John Doe"
}

and Patient model looks basiclally the same (only id and name) and two models are connected with HasManyThrough relationship with through model called Appointment as in the docs. https://loopback.io/doc/en/lb2/HasManyThrough-relations.html

My question is, when you GET to /api/physicians url how can you query the response so it includes the appointment date as well as patient for every physician?

Wanted output:

{
  "id": "4654654654654654654",
  "name": "John Doe",
  "patients": [
     { "id": "1321232313", "name": "First Patient", "appointment_date": 1995-12-17T03:24:00 },
     { "id": "1321232313", "name": "Second Patient", "appointment_date": 1995-12-17T03:24:00 }
  ]
}

Field "appointment_date" is the date from the appointment through model and patient names are obtained through nested including of same model.

Any thoughts?

Upvotes: 1

Views: 4715

Answers (1)

IftekharDani
IftekharDani

Reputation: 3729

Use Nested Include Just check link Its help.

Please check this Code :

    physicians.find(
{
  include: {
  "relation": "Appointment",
  "scope": {
    "fields": ["id", "patientId", "AppointmentDate", "physiciansId"], /*need to include both Person and PersonID fields for this to work*/
    "include": {
      "relation": "patient",
      "scope": {
        "fields": {"id": true, "patienName": true},
         where: {id: patientId},
      }
    }
  }
}
}

Upvotes: 3

Related Questions