Php 我们如何建立一个多层次的关联
我有四张桌子。我想在一个表上实现一个查询,并从相关表中获取数据 在CakePHP中,我们使用Php 我们如何建立一个多层次的关联,php,mysql,laravel,cakephp,associations,Php,Mysql,Laravel,Cakephp,Associations,我有四张桌子。我想在一个表上实现一个查询,并从相关表中获取数据 在CakePHP中,我们使用contain,但在Laravel中我不知道 国家, 各国 城市 地点 型号代码 class Country extends Model { public function states() { return $this->hasMany('App\State'); } } class State extends Model { public func
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->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
我必须查询国家,我还想检索国家
$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循环获取城市等
dd($country->toarray()); // to check the output
示例
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->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
查看文档了解更多信息:$country=country::with('states.city.location')->where('id',1)->first();我不明白你的意思!您在最后:->第一个“语法错误”中错过了>