Issue
I have three tables, structure are as follows:
products:
id | name | slug | price
product_attributes:
id | attribute_id | value | qty | product_id
attributes :
id | code | name
Now i'm getting the product and the attributes selected for this particular product using the following relationships but i also want the code and name of the attribute from the third table i.e. attributes:
ProductController.php:
public function show($slug)
{
$product = $this->productRepository->findProductBySlug($slug);
return view('site.pages.product', compact('product'));
}
ProductRepository.php
public function findProductBySlug($slug)
{
$product = Product::with('attributes')->where('slug', $slug)->first();
return $product;
}
Model : Product.php
public function attributes()
{
return $this->hasMany(ProductAttribute::class);
}
getting data on view with following code:
{{ dd($product->attributes) }}
but i also want data from the third table i.e. attributes
Solution
Use Many to Many relationship and withPivot to get the pivot attributes:
// Product Model:
public function attributes()
{
return $this->belongsToMany(Attribute::class, 'product_attributes')->withPivot('value', 'qty');
}
// Attribute Model:
public function products()
{
return $this->belongsToMany(Product::class, 'product_attributes')->withPivot('value', 'qty');
}
So you can get attributes and the pivot's datas:
@foreach($product->attributes as $attr)
{{$attr->pivot->value}}
{{$attr->pivot->qty}}
{{$attr->code}}
{{$attr->name}}
@endforeach
Answered By - TsaiKoga
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.