编程语言
首页 > 编程语言> > php – 我们如何进行laravel多级关联

php – 我们如何进行laravel多级关联

作者:互联网

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

在CakePHP中,我们使用包含但在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进行查询,我还要检索State

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

像这样,但我怎样才能获得城市 – >这个位置.我需要手动进行另一个查询吗?在CakePHP中我们使用contains,但在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

标签:php,mysql,laravel,associations,cakephp
来源: https://codeday.me/bug/20190628/1311018.html