我们如何建立laravel多级关联

How can we make a laravel multilevel association

我有 4 个 table。我想对一个 table 执行查询并从相关的 table 中获取数据。

在 CakePHP 中,我们使用 contain 但在 Laravel 中我不知道。

型号代码

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 {

}

我必须查询国家/地区,我还想检索州

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

就像那样,但是我怎么能用这个得到cities -> location。我需要手动进行另一个查询吗?在 CakePHP 中我们使用 contain,但在 Laravel 中,没有类似的关键字或功能吗?

我猜这应该可以解决问题

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

你会得到 id = 1 的国家和它的州,每个州都有城市等等

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

然后使用一个 foreach 循环获取州,并在其中使用另一个 foreach 循环获取城市等

举例

{{$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

查看文档以获取更多信息:EAGER LOADING