簡體   English   中英

從數據透視表中獲取特定列值

[英]Getting a specific column value from a pivot table

問題

我有三個桌子, shopsproductsproduct_shop作為數據透視表。 ShopProduct使用belongsToMany (多對多)相關。 將新Product插入數據庫時​​,在我的表單中,我可以為每個Shop指定價格。 提交表單時, product_idshop_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM