2017-09-07 45 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时,它工作正常。我不知道为什么,也许团体是一些保留字或什么。