【发布时间】:2023-03-26 21:06:01
【问题描述】:
我正在使用 hasMany 和 belongsTo 处理 Laravel 关系。它适用于 hasMany 关系,但我在 belongsTo 上遇到问题,用于收集 foreach 循环。这是我的categories 表。
id name
--------------
1 food
还有products 表。
id name category_id
----------------------------------
1 pizza 1
2 hamburger 1
下面是hasMany产品型号。
# Product.php
public function products()
{
return $this->hasMany(Product::class);
}
下面是belongsTo类别模型。
# Category.php
public function category()
{
return $this->belongsTo(Category::class, 'id');
}
我在刀片中遇到错误:
试图获取非对象的属性
<tbody>
@foreach ($products as $product)
<tr>
<td> {{ $product->category->name }} </td>
</tr>
@endforeach
</tbody>
任何关于这方面的建议或指导将不胜感激,谢谢
【问题讨论】:
标签: php laravel laravel-5 relationship belongs-to