该集合实例上不存在属性[subcategory] ​​

时间:2019-09-04 05:39:58

标签: laravel eloquent eloquent--relationship

第一次使用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');
}
}

子类别模型

class子类别扩展了Model {     受保护的$ fillable =([         'category_id',         '名称'     ]);

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

@foreach($ cat->子类别为$ item){{$$ item-> name}}
    @endforeach