she hates me
she hates me

Reputation: 1272

Relation with pivot table

I've three tables and I would like to use pivot table data when getting results.

These tables are products, store, store_products, cart_items and their fields are below:

My CartItem model is like

class CartItem extends Model
{
    public function product()
    {
        return $this->belongsTo('App\Product');
    }

    public function store()
    {
        return $this->belongsTo('App\Store');
    }

}

When I call CartItem::with('product')->get(), I would like it to return product data (from product table and store_price, store_slug from store_products) with matching cart_items.store_id and cart_items.product_id from pivot table "store_products".

How can I create this relation by on my CartItem model? If possible, by just using Eloquent ORM functions instead of query builder or raw queries.

Upvotes: 0

Views: 144

Answers (1)

Balraj Allam
Balraj Allam

Reputation: 611

In products Model add,

public function stores(){
    return $this->belongsToMany(Store::class)->withPivot('store_price', 'store_slug');
}

In Store Model add,

public function products(){
    return $this->belongsToMany(Products::class)->withPivot('store_price', 'store_slug');
}

Then call,

CartItem::with(['product.stores'])->get();

For more explanation read this article:

http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

Upvotes: 0

Related Questions