Sandeep Sandeep - 5 months ago 18
MySQL Question

How can we make in laravel multilevel association

I have 4 tables. I want to implement query on one table and getdata related tables. Please help me how can I do this. In cakphp we use

contain
but laravel I have no idea.

countries,
states,
cities,
locations

Model code
Country Model

class Country extends Model {
public function states() {
return $this->hasMany('App\State');
}
}

class State extends Model {
public function city() {
return $this->hasMany('App\City');
}
}


class City extends Model {
public function location() {
return $this->hasMany('App\Location');
}
}
class Location extends Model {

}


I have make query on country and get state

$country = Country::where('id',1);
$country->states


like that but how can I get
cities -> location
with this. May make another query manually? In cakephp we use
contain
, In lavavel no such these type of keyword in this?

Please help me

Answer

This should do the trick i guess

$country = Country::with('states.city.location')->where('id',1)-first();

You will get the country of id = 1 and it's states, and each of it's states will have the citys ..etc

dd($country->toarray()); // to check the output

Then use a foreach loop to fetch the states and another foreach loop inside it to fetch the cities ...etc

exemple

{{$country->name}}

@foreach($country->states as $state)
  {{$state->name}}
  @foreach($state->city as $city)
    {{$city->name}}
    @foreach($city->location as $location)
    {{$location->name}}
    @foreach
  @foreach
@foreach

Check Docs for more info : EAGER LOADING

Comments