laravel - 此集合实例上不存在属性 [子类别]
问题描述
第一次处理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'));
}
解决方案
你在 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
是一个集合。
推荐阅读
- intellij-idea - IntelliJ:如何更改参数信息弹出窗口的颜色
- python - 如何访问同一个 Docker 容器中的其他文件?
- apache-spark - 使用 Pandas UDF 进行 Pyspark 流式传输
- ionic-framework - UPI 与 ionic 应用程序的集成没有通过
- javascript - 如何将 HEIC/HEIF 图像转换为 ReactJs 中的图像
- javascript - 用玩笑测试 setTimeout 上的毫秒参数
- r - 在R中添加数据框的相应列
- emacs - init.el 中定义的重复 TODO 关键字
- java - mongoDB Atlas 异常打开套接字
- node.js - 返回错误时如何将键附加到错误属性