【问题标题】:Laravel BelongsToMany with two pivot tableLaravel BelongsToMany 有两个数据透视表
【发布时间】:2018-09-26 13:27:21
【问题描述】:

我的表结构如下:

产品

  • 身份证

product_formats

  • 身份证
  • product_id

product_prices

  • 身份证
  • product_format_id
  • market_id

市场

  • 身份证

一种产品可以有多种格式,每种格式都有自己的价格,属于不同的市场。如何从 Product 模型中检索市场列表?

我以前只有一个数据透视表,但现在我有两个数据透视表。

class Product extends Model
{
    public function markets()
    {
        return $this->belongsToMany(Market::class);
    }
}

更新

为了得到我想要的结果,我做了以下事情:

public function markets()
{
    return Market::whereIn('id', $this->prices()->distinct()->pluck('market_id')->toArray());
}

但是,我想知道是否有办法通过关系来实现这一点。

【问题讨论】:

  • 简单。只需在productsproduct_formats 之间建立one to many 关系,在product_formatsmarkets 之间建立many to many 关系
  • 然后,如果您想从一个产品中检索市场列表,只需执行$product->product_format[0]->markets。我说format[0]是因为一对多的关系
  • @LuisfelipeDejesusMunoz 那不是只检索我的第一种格式的市场吗?我想要每种格式的所有独特市场。
  • 这取决于您查询数据的方式。如果您想要单一产品的所有独特市场,您可以执行markets->whereHas("product_formats.products", function($query){$query->where("id", myProductId);})->get() 之类的操作

标签: laravel laravel-5


【解决方案1】:

您需要在模型中建立关系。

产品型号:

public function productFormats()
{
  return $this->belongTo(ProductFormatsModel::class);
}

ProductFormatsModel:

public function productPrices()
{
  return $this->belongTo(ProductPricesModel::class);
}

ProductPricesModel:

public function markets()
{
  return $this->hasOne(MarketsModel::class);
}

在控制器中:

foreach($product->productFormats as $productFormat) 
{
  foreach($productFormat->productPrices as $productPrice)
  {
     var_dump($productPrice->markets);
  }
}

针对独特市场

在 ProductModel 中:

public function productPrices()
    {
        return $this->hasManyThrough(
                      'App\ProductPricesModel', 
                      'App\ProductFormatsModel',
                      'product_id', 
                      'product_format_id'
                      'id',
                      'id'
                     );
    }

在控制器中

foreach($product->productPrices as $productPrice)
{
  var_dump($productPrice->markets)
}

【讨论】:

  • 这不会给我独特的市场。我还想要一个集合中的市场。
  • @ChinLeung 独特市场是什么意思。 2个相同的市场可以匹配一种产品吗?所以对于每个产品市场都将在一个单独的集合中
  • 这不行,市场在不同的集合中。我希望它们都在同一个集合中。
  • @ChinLeung 所以你想要市场-> 产品,而不是产品-> 市场?
  • @ChinLeung 只是不明白,所有属于产品的市场都会在一个集合中,你还想在那里洗澡?
猜你喜欢
  • 2014-12-15
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2014-09-16
  • 2018-04-10
  • 1970-01-01
相关资源
最近更新 更多