Reputation: 1993
I've got three tables, shops
, products
, and product_shop
as the pivot table. The Shop
and Product
are related using a belongsToMany
(Many to Many). When inserting a new Product
into the database, in my form I can specify a price for each Shop
. When submitting the form, the product_id
and shop_id's
are being inserted into the Pivot table with their related prices.
My question is, how do I retrieve only the price of a product from the pivot table, when specifying a shop_id
? Ultimately, my goal is described below, and there might be a better solution for this.
Furthermore, why I need this is the following. I have a categories
table as well. And in my index view
I want to do something like this:
@foreach($categories as $category) // All categories
{{ $category->name }} // Display the name of the category
@foreach($category->products as $product) // Loop through all related products for each category
{{ $product->name }}
{{ $product->price }}
@endforeach
@endforeach
Now the trick is that the price is coming from the pivot table. I want to display the above based on the shop_id
. Ideally, I just want to create a query where I select everything that I need, and then use that collection in my foreach, so I do not have to use specific methods in my views. So basically what I need is something along the lines of this:
select
categories->with('products') // Select all categories while eager loading the products
price // Collected from the pivot table where the shop_id is equal to the given shop_id
CREATE TABLE `categories` (
`id`,
`user_id`,
`name`,
`created_at`,
`updated_at`
)
CREATE TABLE `shops` (
`id`,
`user_id`,
`name`,
`created_at`,
`updated_at`
)
CREATE TABLE `products` (
`id`,
`user_id`,
`category_id`,
`name`,
`created_at`,
`updated_at`
)
CREATE TABLE `product_shop` (
`id`,
`product_id`,
`shop_id`,
`price`,
`created_at`,
`updated_at`
)
Upvotes: 3
Views: 80
Reputation: 1993
Figured it out myself in the end, since all the answers above were not 100% what I was looking for, unfortunately.
public function price($shop_id)
{
return $this->shops()->where('shop_id', $shop_id)->first()->pivot->price;
}
Upvotes: 0
Reputation: 3704
In your Product
model define this
public function shops () {
return $this->belongsToMany(Shop::class)->wirhPivot('price');
}
Then you can
Product::with('shops')->get();
To eager load and the resulting collection will have the price
Upvotes: 1
Reputation: 3266
Using eloquent:
$shop=Shop::where('id',$id)->first();
$shop->pivot->price;
Also, make sure you use ->withPivot
in relation:
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('price');;
}
Upvotes: 1
Reputation: 3551
In your product.php (Model) file define this relation
public function priceCol($shopId)
{
return $this->belongsTo(ProductShop::class,'product_id')->where('shop_id',$shopId);
}
For retrieving the price of a specific product
$product = Product::find(1);
$price = $product->priceCol($shopId)->price;
Upvotes: 1