【问题标题】:Complex relationships in Laravel (hasManyThrough through a pivot table)Laravel 中的复杂关系(hasManyThrough 通过数据透视表)
【发布时间】:2019-04-17 13:05:32
【问题描述】:

所以我有四张桌子。

  • products
  • skus
  • sku_attribute
  • attributes

每个product 都有很多skus。每个sku 有很多attributes。每个attribute 可以有几个skus 与之关联。 sku_attributeskus 和 attributes 之间多对多关系的数据透视表。

这很好用!但是现在,我如何获得与product 关联的所有attributes?

以下代码对我有用。

public function attributes()
{
    return $this->skus->flatMap(function ($sku) {
        return $sku->attributes;
    });
}

但我得到一个错误,因为这不返回一个关系,而是一个集合。

我也尝试使用solution found here。但我无法让它正常工作,因为他们的模型与我的略有不同。 (每个产品都有很多 sku,反之则不然。)

另一个解决方案是在sku_attributes 上为product_id 添加第三列,但我找不到在$sku->attach($attribute_id) 方法上将其默认填充为sku->product->id 的方法。相反,我每次都必须手动调用它,比如$sku->attach($attribute_id, ['product_id' => $sku->product->id])

【问题讨论】:

  • 你使用的是哪个 Laravel 版本?
  • 最新版本,5.7.13
  • 不。当它通过数据透视表时,Has Many Through 似乎不起作用。这是因为我中间有两张桌子,而不仅仅是一张。它来自 Product->Skus->SkuAttributes->Attributes。

标签: laravel laravel-5 eloquent


【解决方案1】:

这最终对我有用。

public function attributes()
{
    return $this->skus->flatMap(function ($sku) {
        return $sku['attributes'];
    });
}

【讨论】:

    【解决方案2】:

    Laravel 对此没有原生支持。

    我为它创建了一个包:https://github.com/staudenmeir/eloquent-has-many-deep

    你可以这样使用关系:

    class Product extends Model
    {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function attributes()
        {
            return $this->hasManyDeep(Attribute::class, [Sku::class, 'sku_attribute']);
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以试试

      public function attributes()
      {
          return Attributes::whereIn('id', function($query){
              return $query->whereHas('skuAttributes', function($query) {
                  return $query->whereHas('products', function($query) {
                      return $query->where('id', $this->id);
                  );
              });
          });
      }
      

      然后在 skuAttributes 模型上为产品创建一个hasManyThrough

      【讨论】:

      • 我尝试了类似的方法,但不幸的是 whereHas 和 whereIn 不返回会引发错误的关系。
      猜你喜欢
      • 2016-08-04
      • 2018-05-02
      • 2015-09-10
      • 1970-01-01
      • 2019-03-05
      • 2016-09-04
      • 2021-08-24
      • 2017-07-22
      • 1970-01-01
      相关资源
      最近更新 更多