【问题标题】:Getting a specific column value from a pivot table从数据透视表中获取特定列值
【发布时间】:2017-01-28 09:54:08
【问题描述】:

问题

我有三个表,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 显示以上内容。理想情况下,我只想创建一个查询,在其中选择我需要的所有内容,然后在我的 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`
)

理想的最终结果(包括从数据透视表中收集的价格):

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    在您的 product.php(模型)文件中定义此关系

    public function priceCol($shopId)
    {
      return $this->belongsTo(ProductShop::class,'product_id')->where('shop_id',$shopId);
    }
    

    用于检索特定产品的价格

    $product = Product::find(1);
    $price = $product->priceCol($shopId)->price;
    

    【讨论】:

    • 可能这就是我要找的:)
    【解决方案2】:

    使用雄辩:

    $shop=Shop::where('id',$id)->first();
    $shop->pivot->price;
    

    另外,请确保您使用 ->withPivot 关联:

    public function products()
    {
        return $this->belongsToMany('App\Product')->withPivot('price');;
    }
    

    【讨论】:

      【解决方案3】:

      在你的 Product 模型中定义这个

      public function shops () {
          return $this->belongsToMany(Shop::class)->wirhPivot('price'); 
      }
      

      那你就可以了

      Product::with('shops')->get();
      

      要急切的加载和产生的集合会有价格

      【讨论】:

        【解决方案4】:

        最后我自己想通了,因为不幸的是,上面所有的答案都不是我想要的 100%。

        public function price($shop_id)
        {
            return $this->shops()->where('shop_id', $shop_id)->first()->pivot->price;
        }
        

        【讨论】:

          猜你喜欢
          • 2017-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-20
          • 2019-09-29
          • 1970-01-01
          相关资源
          最近更新 更多