此集合实例上不存在属性 [子类别] [英] Property [subcategory] does not exist on this collection instance

查看:16
本文介绍了此集合实例上不存在属性 [子类别]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次使用 eloquent 关系.我正在尝试访问 subcategory 方法 但我收到此错误:

First time working with eloquent relationship. I'm trying to access the subcategory method yet I get this error:

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

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

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

New to laravel so any help would be appreciated!

刀片

                <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 Subcategory extends Model{受保护的 $fillable = (['category_id','名称']);

class Subcategory extends Model { 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'));
}

推荐答案

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

You are doing wrong in foreach loop. Your second foreach loop will be like

@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 是一个集合.

your current object is $cat and $categories is a collection.

这篇关于此集合实例上不存在属性 [子类别]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆