user3653474
user3653474

Reputation: 3854

Cannot get data from third table using relation in Laravel

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

Upvotes: 0

Views: 44

Answers (2)

AH.Pooladvand
AH.Pooladvand

Reputation: 2059

First you need to define a relation between Product and ProductAttribute

Model : Product.php

public function attributes()
{
    return $this->hasMany(ProductAttribute::class, 'product_id');
}

Then you need to define a relation between ProductAttribute and Attribute model

Model : Attribute.php

public function attributes()
{
    return $this->hasMany(ProductAttribute::class, 'attribute_id');
}

Then you can eager load relations easily by . notation

public function findProductBySlug($slug)
{
 $product = Product::with('attributes.attributes')->where('slug', $slug)->first();

 return $product;
}

Upvotes: 1

TsaiKoga
TsaiKoga

Reputation: 13394

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

Upvotes: 1

Related Questions