A
A
Alexey Sklyarov2021-09-07 23:17:25
Laravel
Alexey Sklyarov, 2021-09-07 23:17:25

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

clinics table

| id | title | city_id |
|----|-------|---------|
|    |       |         |


cities table

| id | name |
|----|------|
|    |      |


doctor table

| id | full_name |
|----|-----------|
|    |           |


clinic_doctor table

| clinic_id | doctor_id |
|-----------|-----------|
|           |           |



In App\Models\Doctor.phpI 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::classthis 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_idto return the model of cities with id = city_id, but my current method returns the cities for which id = idfrom the table of clinics (id = clinics.id). I tried to change the hasManyThroughfield idto 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

2 answer(s)
A
Alexey Sklyarov, 2021-09-08
@0example

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'
            ]
        );
    }

I
inFureal, 2021-09-08
@inFureal

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 question

Ask a Question

731 491 924 answers to any question