Reputation: 3596
I need to get the list of product categories from the table. 2 tables in total. tblProduct & tblProductCatLink 1 product can have many product category link.
tblProductCatLink consists of product_id, category_id Now from my controller & view, i want to get the list of categories belong to one product.
Product.php
public function productcategorylink(){
return $this->HasMany('App\ProductCategoryLink', 'product_id', 'id');
}
ProductCategoryLink.php
public function projects(){
return $this->hasMany('App\Project', 'id', 'product_id');
}
Controller
foreach ($projects as $project) {
foreach ($project->productcategorylink as $value) {
echo $value->category_id;
}
}
The above code is returning first row of category for the product only. I had 3 rows of records for product 297 in my DB.
Upvotes: 1
Views: 512
Reputation: 163978
I need to access the product category link from the view while I looping the product data
In a controller:
$products = Product::with('productcategorylink')->get();
In view:
@foreach ($products as $product)
@foreach ($product->productcategorylink as $link)
{{ $link->category_id }}
@endforeach
@endforeach
Upvotes: 1
Reputation: 126
You need to call productcategorylink
and projects
. So it would be
$projects = projects();
foreach ($projects as $project) {
$productCategoryLink = $project->productcategorylink();
foreach ($productCategoryLink as $value) {
echo $value->category_id;
}
}
Upvotes: 0