1
votes

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.

2
@Maraboc yes, it's using project model. No wording error here - 1myb

2 Answers

1
votes

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

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