【问题标题】:How can we make a laravel multilevel association我们如何建立一个 laravel 多级关联
【发布时间】:2016-06-22 06:27:29
【问题描述】:

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

在 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 中,没有类似的关键字或功能?

【问题讨论】:

    标签: php mysql laravel cakephp associations


    【解决方案1】:

    我猜这应该可以解决问题

    $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

    【讨论】:

    • $country = Country::with('states.city.location')->where('id',1)->first();
    • 我听不懂你的意思!
    • 你错过了 > 在最后:->第一个“语法错误”
    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2017-01-18
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多