laravel中的嵌套关​​系

时间:2018-10-04 07:29:52

标签: php laravel laravel-5 eloquent

我有以下三种关系模型:

Tour.php

class Tour extends Model
{
    public function category()
    {
        return $this->belongsTo('App\TourCategory', 'category_id');
    }

    public function region()  
    {
        return $this->belongsTo('App\Region');
    }
}

TourCategory.php

class TourCategory extends Model
{
    public function tours()
    {
        return $this->hasMany('App\Tour', 'category_id');
    }
}

Region.php

class Region extends Model
{
    public function tours()
    {
        return $this->hasMany('App\Tour');
    }
}

我正在尝试从每个地区获取具有特定旅游类别的所有旅游。

例如 获取洛矶山脉地区,黄石,优胜美地的所有徒步旅行

我尝试输入以下代码:

public function trekRegions( View $view)
{
    $category = TourCategory::where('slug','=','hiking')->first();
    $tours = $category->tours()->with('region')->get(['region_id']);
    $regions = $tours->pluck('region')->unique();
    $view->with('tregions',$regions);
}

我想在Mega Menu Navigation Bar中将所有游览名称打印在区域名称下方,但是上面的代码确实允许我打印区域名称,但也可以打印其他类别的游览。

我的前端代码

@if(!empty($tregions)) @foreach($tregions as $region)
<div class="col-sm-3">
  <strong class="title sub-link-opener">{{ $region->name }}</strong>
  <ul class="header-link">
    @foreach($region->tours as $tour)
    <li>
      <a href="{{ route('frontend-tourDetail',[$tour->slug]) }}">{{ $tour->title }}</a>
    </li>
    @endforeach
  </ul>
</div>
@endforeach @endif

2 个答案:

答案 0 :(得分:1)

根据您的特定要求。

过滤Regions which has hiking tours并急切加载hiking tours

$regions = Region::whereHas('tours', function ($toutQuery) {
    $tourQuery->whereHas('tourCategory', function ($categoryQuery) {
        $categoryQuery->where('name', 'hiking');
    });
}) // filter to match your requirements.
->with([
    'tours' => function ($toursQuery) {
        $toursQuery->whereHas('tourCategory', function ($categoryQuery) {
            $categoryQuery->where('name', 'hiking');
        });
    }
]) // load matching tours.
->get();

答案 1 :(得分:0)

您可以在一个查询中完成

$tours = Tour::whereHas('category', function($c) {
    $c->where('slug', 'hiking');
})->whereHas('region', function($c) {
    $c->where('title', 'Rocky Mountain Region');
})->get();