Reputation: 1272
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:
products (id, name, price)
store (id, name etc.)
store_products (store_id, product_id, store_price, store_slug)
cart_items (id, user_id, product_id, store_id, quantity)
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
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