jeudi 4 octobre 2018

Nested relationship in laravel

I have three models in following manner of relationship:

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');
  }
}

I'm trying to get all tours with specific tour category from particular region.

For example Get all hiking tours from Rocky Mountain Region

I've tried to the following code:

 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);
  }

The above code is returning all tours that has listed Rocky Mountains in its region. i.e: fishing and others

What sort of changes should I make on the query in-order to get expected result ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire