首页 > 解决方案 > 此集合实例上不存在属性 [子类别]

问题描述

第一次处理eloquent关系。我正在尝试访问subcategory method但我收到此错误:

此集合实例上不存在属性 [子类别]。

laravel 新手,任何帮助将不胜感激!

                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">Category</th>
                            <th scope="col">Sub-category</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($categories as $cat)
                            <tr>
                                <td scope="row">{{$cat->name}}</td> 

                                 //error here
                                @foreach ($categories->subcategory as $item)
                                    <td>{{$item->name}}</td>
                                @endforeach

                            </tr>
                            @endforeach
                    </tbody>
                </table>

类别模型

class Category extends Model
{
protected $fillable = ([
    'name'
]);

public function subcategory(Type $var = null)
{
    # code...
    return $this->hasMany(Subcategory::class,'category_id','id');
}
}

子类别模型

类子类别扩展模型 { protected $fillable = ([ 'category_id', 'name' ]);

public function category(Type $var = null)
{
    # code...
    return $this->belongsTo(Category::class);
}
}

控制器

public function create()
{
    $categories = Category::all();
    // dd($categories);
    return view('settings.create', compact('categories'));
}

标签: laraveleloquenteloquent-relationship

解决方案


你在 foreach 循环中做错了。你的第二个 foreach 循环就像

@foreach ($categories as $cat)
    <tr>
        <td scope="row">{{$cat->name}}</td> 
        @foreach ($cat->subcategory as $item)
        <td>{{$item->name}}</td>
        @endforeach

    </tr>
@endforeach

您当前的对象是$cat并且$categories是一个集合。


推荐阅读