Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我们如何建立一个多层次的关联_Php_Mysql_Laravel_Cakephp_Associations - Fatal编程技术网

Php 我们如何建立一个多层次的关联

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

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

在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->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();我不明白你的意思!您在最后:->第一个“语法错误”中错过了>