简体   繁体   中英

Display Category Name With Category ID from Product - Laravel

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.

My Database:

Category: CategoryID, CategoryName

Product: ProductID, Name, Des, ProductCategoryID

Product Model:

protected $table ='products';

protected $primaryKey = 'ProductID';

public $timestamps = false;

public function Category(){
   return $this->belongsTo('App\Category','ProductID','CategoryID');
}

Category Model:

protected $table = 'productcategories';

public function Product(){
  return $this->hasMany('App\Product','ProductCategoryID','ProductID');
}

My Controller:

 public function danhsachsanpham(){

$sanpham = Product::all();
return view('admin/products/danhsach', ['sanpham'=> $sanpham]);

}

My Views:

            <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>

And I get an Error:

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.

Thanks

You'd get the CategoryName through the Category() relationship method:

<td>{{$sp->Category()->first()->CategoryName}}</td>

Or shorter:

<td>{{$sp->Category->CategoryName}}</td>

Edit: Your relationships methods are using wrong foreign keys. Try:

Product Model:

public function Category() 
{
    return $this->belongsTo('App\Category', 'ProductCategoryID', 'CategoryID');
}

Category Model (note plurality naming of the method: Product s ) :

public function Products()
{
    return $this->hasMany('App\Product', 'ProductCategoryID');
}

I would like to update the answer according to Laravel 8 .

Product Model:

public function Category() 
{
    return $this->belongsTo('App\Models\Category', 'ProductCategoryID', 'CategoryID');
}

Category Model:

public function Products()
{
    return $this->hasMany('App\Models\Product', 'ProductCategoryID');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM