加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 19:42:59 所属栏目:大数据 来源:网络整理
导读:我有4张桌子.我想在一个表上实现查询并从相关表中获取数据. 在CakePHP中,我们使用包含但在Laravel我不知道. 国家, 州, 城市, 地点 型号代码 class Country extends Model { public function states() { return $this-hasMany('AppState'); }}class State ex
我有4张桌子.我想在一个表上实现查询并从相关表中获取数据.

在CakePHP中,我们使用包含但在Laravel我不知道.

>国家,
>州,
>城市,
>地点

型号代码

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


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


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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读