0
votes

I have a problem with laravel relationships.

I have 3 models:

City —(hasMany) —>Clinic—(hasMany) —>Stock

Stock —(belongsTo) —>Clinic —(belongsTo) —>City

I need get all cities which has stocks, looks like «Stock->cities». I can write sql-query:

SELECT ct.id, ct.name
FROM CfgCity as ct
RIGHT JOIN lr_clinics AS cl ON(ct.id=cl.city_id)
RIGHT JOIN lr_clinic_stocks AS st ON(cl.id=st.clinic_id)
WHERE st.deleted_at IS NULL
GROUP BY ct.id

But I want decision in laravel-orm, because it’s more readable and I don’t need write names of rows and tables. Is it possible? Thanks.

1
You need to get better at reading the documentation.Kyslik

1 Answers

2
votes

From your question it is clear that city has relation with clinic and clinic has relation with stock that means city has relation with stock through clinic. That you can define it using laravel relationship.

City Model

class City extends Model {

    public function clinics(){
       return $this->hasMany(Clinic::class);
    }

    public function stocks(){
       return $this->hasManyThrough(Stock::class, Clinic::class);
    }
}

Fetch data

$cities = City::whereHas('stocks')->get();

For details you can check https://laravel.com/docs/5.6/eloquent-relationships#has-many-through