Answer the question
In order to leave comments, you need to log in
How to get a list of cities in which a doctor works, through the list of clinics of this doctor?
There are 3 models: Doctor, Clinic, City. Each city is associated with a clinic (one-to-many), a doctor can work in several clinics, so a many-to-many relationship is established for these two models and a clinic_doctor pivot table is created
| id | title | city_id |
|----|-------|---------|
| | | |
| id | name |
|----|------|
| | |
| id | full_name |
|----|-----------|
| | |
| clinic_id | doctor_id |
|-----------|-----------|
| | |
App\Models\Doctor.php
I described the relationship:public function cities()
{
return $this->hasManyThrough(
City::class,
ClinicDoctor::class,
'doctor_id', // clinic_doctor table
'id', // cities table
'id',
'clinic_id', // clinic_doctor table
);
}
ClinicDoctor::class
this is a pivot table clinic_doctor
. This method returns an invalid relation. From the doctor, I get a list of all the clinics where he works, and from these clinics I have to take the field city_id
to return the model of cities with id = city_id
, but my current method returns the cities for which id = id
from the table of clinics (id = clinics.id). I tried to change the hasManyThrough
field id
to city_id
, but it didn't work. Where am I making a mistake?
Answer the question
In order to leave comments, you need to log in
The solution to the problem, perhaps it will be useful to someone. Installed eloquent-has-many-deep . The relationship is described as follows:
public function cities()
{
return $this->hasManyDeep(
City::class,
['clinic_doctor', Clinic::class],
[
'doctor_id',
'id',
'id'
],
[
'id',
'clinic_id',
'city_id'
]
);
}
Everything is written in the documentation. Binding keys not spelled correctly
class Project extends Model
{
public function deployments()
{
return $this->hasManyThrough(
Deployment::class,
Environment::class,
'project_id', // Foreign key on the environments table...
'environment_id', // Foreign key on the deployments table...
'id', // Local key on the projects table...
'id' // Local key on the environments table...
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question