我们如何进行laravel多层次关联

时间:2016-06-21 05:08:03

标签: php mysql laravel cakephp associations

我有4张桌子。我想在一个表上实现查询并从相关表中获取数据。

在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中,没有类似的关键字或功能吗?

1 个答案:

答案 0 :(得分:3)

这应该是我猜的伎俩

$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