[英]Getting a specific column value from a pivot table
我有三個桌子, shops
, products
和product_shop
作為數據透視表。 Shop
和Product
使用belongsToMany
(多對多)相關。 將新Product
插入數據庫時,在我的表單中,我可以為每個Shop
指定價格。 提交表單時, product_id
和shop_id's
相關價格插入數據透視表中。
我的問題是,在指定shop_id
時,如何僅從數據透視表中檢索產品的價格? 最終,我的目標如下所述,可能有更好的解決方案。
此外,為什么我需要這個是以下。 我也有一個categories
表。 在我的index view
我想做這樣的事情:
@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
現在的訣竅是價格來自數據透視表。 我想根據shop_id
顯示上面的shop_id
。 理想情況下,我只想創建一個查詢,在其中我選擇我需要的所有內容,然后在我的foreach中使用該集合,因此我不必在視圖中使用特定方法。 所以我基本上需要的是這樣的事情:
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`
)
在product.php(Model)文件中定義此關系
public function priceCol($shopId)
{
return $this->belongsTo(ProductShop::class,'product_id')->where('shop_id',$shopId);
}
用於檢索特定產品的價格
$product = Product::find(1);
$price = $product->priceCol($shopId)->price;
使用雄辯:
$shop=Shop::where('id',$id)->first();
$shop->pivot->price;
另外,請確保使用->withPivot
:
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('price');;
}
在您的Product
型號中定義此項
public function shops () {
return $this->belongsToMany(Shop::class)->wirhPivot('price');
}
然后你可以
Product::with('shops')->get();
急切加載和產生的收集將有價格
最后我自己弄清楚了,因為不幸的是,上面的所有答案都不是我想要的100%。
public function price($shop_id)
{
return $this->shops()->where('shop_id', $shop_id)->first()->pivot->price;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.