2017-09-07 44 views
0

我有過濾器屬於過濾組 Filter.php:Laravel 5.4不能得到elloquent模型的關係

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Filter extends Model 
{ 
    public function group() 
    { 
     return $this->belongsTo('App\FilterGroup'); 
    } 

    public function products() 
    { 
     return $this->belongsToMany('App\Product', 'product_filters'); 
    } 

    public function categories() 
    { 
     return $this->belongsToMany('App\Filter', 'category_filter'); 
    } 
} 

,並且有許多與過濾器 Category.php許多關係類:

namespace App; 

use App\Events\CategoryDelete; 
use Illuminate\Database\Eloquent\Model; 

class Category extends Model 
{ 
    protected $events = [ 
     'deleting' => CategoryDelete::class 
    ]; 

    protected $table = 'categories'; 

    public function parent() 
    { 
     return $this->belongsTo('App\Category', 'parent_id'); 
    } 

    public function children() 
    { 
     return $this->hasMany('App\Category', 'parent_id'); 
    } 

    public function parents() 
    { 
     $parentCategories = collect([]); 

     $parent = $this->parent; 

     while (!is_null($parent)) { 
      $parentCategories[] = $parent; 

      $parent = $parent->parent; 
     } 

     return $parentCategories->reverse(); 
    } 

    public function products() 
    { 
     return $this->hasMany('App\Product'); 
    } 

    public function filters() 
    { 
     return $this->belongsToMany('App\Filter', 'category_filter'); 
    } 

    public function hasFilter($filter_id) 
    { 
     foreach ($this->filters as $filter) { 
      if ($filter->id == $filter_id) { 
       return true; 
      } 
     } 

     return false; 
    } 

    public function getFilterGroups() 
    { 
     $filterGroups = collect([]); 

     foreach ($this->filters as $filter) { 
      if (!$filterGroups->has($filter->group->id)) { 
       $filterGroups[$filter->group->id] = $filter->group; 
      } 
     } 

     return $filterGroups; 
    } 
} 

而在分類視圖我想與他們的過濾器組一起顯示的過濾器,但是當我嘗試以下方法:

@foreach($category->filters as $filter) 
    {{ $filter->group->name }} 
    <br> 
@endforeach 

它拋出試圖獲取非對象的屬性例外 爲什麼我無法獲得過濾器組?

+1

有兩種選擇會發生這種情況:1)您正在迭代的其中一個篩選器沒有組。 2)你的關係設置不正確 – devk

+0

類別似乎沒有在模型中定義的「過濾器」關係 –

+0

@DeepanshSachdeva它是第5種方法:) –

回答

0

我將Filter模型中的group()方法更改爲filterGroup,現在當我調用$ filter-> filterGroup時,它工作正常。我不知道爲什麼,也許團體是一些保留字或什麼。