第一次与eloquent
关系。我正在尝试访问subcategory method
但我收到这个错误:
此集合实例上不存在属性 [子类别]。
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');
}
}
子品类模型
类子类别扩展模型
{
受保护的 $fillable = ([
'类别_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'));
}
你在 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
and $categories
是一个集合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)