Laravel 5.4无法获得雄辩模型的关系

时间:2017-09-07 14:53:55

标签: php laravel laravel-5.4 relationship

我有属于过滤器组的过滤器 Filter.php:

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 个答案:

答案 0 :(得分:0)

我将Filter模型中的group()方法更改为filterGroup,现在当我调用$ filter-&gt; filterGroup时,它工作正常。我不知道为什么,也许群体是一些保留的词或什么。