【发布时间】:2021-09-24 03:40:38
【问题描述】:
我已经找到了这个答案,但它对我不起作用 (Laravel - displaying categories by id)
我无法在产品列表页面中显示类别名称。
我的数据库:
类别:CategoryID、CategoryName
产品:ProductID、名称、Des、ProductCategoryID
产品型号:
protected $table ='products';
protected $primaryKey = 'ProductID';
public $timestamps = false;
public function Category(){
return $this->belongsTo('App\Category','ProductID','CategoryID');
}
类别模型:
protected $table = 'productcategories';
public function Product(){
return $this->hasMany('App\Product','ProductCategoryID','ProductID');
}
我的控制器:
public function danhsachsanpham(){
$sanpham = Product::all();
return view('admin/products/danhsach', ['sanpham'=> $sanpham]);
}
我的观点:
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr align="center">
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Category Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($sanpham as $sp): ?>
<tr class="odd gradeX" align="center">
<td>{{$sp->ProductID}}</td>
<td>{{$sp->ProductName}}</td>
<td>{{$sp->ProductLongDesc}}</td>
<td>{{$sp->ProductCategoryID->CategoryName}}</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
我得到一个错误:
Trying to get property of non-object (View: C:\xampp\htdocs\banhang\resources\views\admin\products\danhsach.blade.php)
我错在哪里?请告诉我如何解决它。
谢谢
【问题讨论】: