midhun prakash
midhun prakash

Reputation: 31

how to get data from pivot table inside a many to one relation in laravel 5.6

I have 3 tables name like "product" , "user", "product_type" so in my case user and product_type having many to many relationship and user and product having one to many relationship and product and product_type having one to one relationship.

I create one pivot table for user and product_type. inside that pivot table, I added one more column for description. so in product listing page I need to display description from that pivot table.

My code look like this:

Product::with('user)->with('product_type')->get();

Upvotes: 0

Views: 314

Answers (1)

Kinjal
Kinjal

Reputation: 91

To get extra fields from pivot table you need to use withPivot in function of your model Like this:

public function product_type() {
      return $this->belongsToMany('App\Product','product_type','product_id','user_id')->withPivot('column1', 'column2');
    }

you may also refer laravel docs for it:

https://laravel.com/docs/5.7/eloquent-relationships

Upvotes: 1

Related Questions