显示具有产品的类别ID的类别名称-Laravel [英] Display Category Name With Category ID from Product - Laravel
问题描述
我已经找到了这个答案,但是它对我不起作用( Laravel-按类别显示类别id )
I already found this answer but it doesn't work for me (Laravel - displaying categories by id)
我无法在产品列表"页面中显示类别名称.
I can't display Category Name in Product List Pages.
我的数据库:
类别:CategoryID,CategoryName
Category: CategoryID, CategoryName
产品:ProductID,名称,Des,ProductCategoryID
Product: ProductID, Name, 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)
我哪里错了?请告诉我如何解决.
Where I was wrong ? Please show me how to fix it.
谢谢
推荐答案
您将通过Category()
关系方法获得 CategoryName :
You'd get the CategoryName through the Category()
relationship method:
<td>{{$sp->Category()->first()->CategoryName}}</td>
或更短:
<td>{{$sp->Category->CategoryName}}</td>
编辑:您的关系方法使用了错误的外键.试试:
Your relationships methods are using wrong foreign keys. Try:
产品型号:
public function Category()
{
return $this->belongsTo('App\Category', 'ProductCategoryID', 'CategoryID');
}
类别模型(注意该方法的多个命名:Product s ):
Category Model (note plurality naming of the method: Products) :
public function Products()
{
return $this->hasMany('App\Product', 'ProductCategoryID');
}
这篇关于显示具有产品的类别ID的类别名称-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!