属性 [子类别] 在此 collection 实例上不存在

Property [subcategory] does not exist on this collection instance

第一次与 eloquent 关系合作。我正在尝试访问 subcategory method 但出现此错误:

Property [subcategory] does not exist on this collection instance.

laravel 的新手,如有任何帮助,我们将不胜感激!

blade

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

子类别模型

class 子类别扩展模型 { 受保护的 $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'));
}

您正在调用 $categories 集合中的 subcategory,而不是在一个模型 $cat 上。因此,将您的 @foreach 方法更改为

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

你在 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是一个集合。

我的解决方案:

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