One to many/inverse relationship - Laravel -


this seems simple enough can't seem figure out.

i have below models

city -> hasmany locations

locations -> hasmany restaurants

restaurants -> belongsto locations

this means restaurant linked city via locations

now want find restaurants in particular city based location provided not restricted location rather city.

the values provided city name , location name. can city_id , location_id

// city locations $city = city::with('locations')->where('value', $c)->first(); $city_id = $city->id;  // location id $location = location::where('value', $l)->first(); $location_id = $location->id; 

so $restaurants query should find restaurants location part of location of $city.

how can achieve this?

you can define hasmanythrough relationship -

class city extends model {     public function locations()     {         return $this->hasmany('app\location');     }     public function restaurants()     {         return $this->hasmanythrough('app\restaurant', 'app\location');     } }  class location extends model {     public function city()     {         return $this->belongsto('app\city');     }     public function restaurants()     {         return $this->hasmany('app\restaurant');     } } class restaurant extends model {     public function location()     {         return $this->belongsto('app\location');     }     public function city()     {         return $this->belongsto('app\city');     } } 

check out docs here.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -