【问题标题】:Laravel Dynamic Polymorphic RelationLaravel 动态多态关系
【发布时间】:2020-07-21 23:44:49
【问题描述】:

所以我试图在 Laravel 中为订单项目建立动态关系。我有 3 种主要类型的模型:

  • 订购
  • 订购商品(有 orderable_type 和 orderable_id 表示产品型号)
  • 产品(多种型号)

我的目标是让 Order 模型能够拥有订单项目,但也包括它们各自的产品模型(可订购)。

这些是我的模型:

class Order extends Model
{
    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }
}

class OrderItem extends Model
{
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function orderable()
    {
        return $this->morphTo();
    }
}

class ProductType extends Model
{
    public function orderItem()
    {
        return $this->morphOne(OrderItem::class, 'orderable');
    }
}

所以,当我打电话给Order::with('items')->get() 时,我得到了\App\Models\OrderItem 的集合:

Illuminate\Database\Eloquent\Collection {#4059
  all: [
    App\Models\Order {#4016
      id: 1,
      ...
      items: Illuminate\Database\Eloquent\Collection {#4026
        all: [
          App\Models\OrderItem {#4063
            id: 1,
            orderable_type: "ProductType",
            orderable_id: 1,
            ...
          },
        ],
      },
    },
  ],
}

而我期望拥有的是:

Illuminate\Database\Eloquent\Collection {#4059
  all: [
    App\Models\Order {#4016
      id: 1,
      ...
      items: Illuminate\Database\Eloquent\Collection {#4026
        all: [
          App\Models\OrderItem {#4063
            id: 1,
            orderable_type: "ProductType",
            orderable_id: 1,
            orderable: App\Models\Products\ProductType {
              ...
            }
            ...
          },
        ],
      },
    },
  ],
}

所以它是一种嵌套的with(),但不知道如何实现它。目的是将所有内容都放在一个 Eloquent 调用中,而不是事后调用关系(也意味着在 API 资源上)。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您正在寻找nested eager loading。您可以在您的情况下使用它们,例如:

    Order::with('items.orderable')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2017-02-28
      • 2016-01-26
      • 1970-01-01
      相关资源
      最近更新 更多