gpt4 book ai didi

php - 我们如何建立一个 laravel 多级关联

转载 作者:可可西里 更新时间:2023-11-01 07:34:21 25 4
gpt4 key购买 nike

我有 4 张 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 并且我还想检索 State

$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

关于php - 我们如何建立一个 laravel 多级关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37936000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com