Laravel Eloquent 与条件的双重关系
Laravel Eloquent double relation with condition
我有三个模型,数据如下:
产品
- id
- 名字
- 描述
变体
- id
- 颜色
- 类型
- 私人
- product_id
图片
- url
- variant_id
所以关系是:
- 产品有许多变体
- 变体有许多图片
我需要获得所有变体的 collection,包括 parent 产品,因为我还需要它的名称并包括与变体相关的图像,以及条件(在变体上) ->where('type', 'OPT') 和 ->where('private', false)。
我尝试使用原始 SQL 查询来完成此操作,但我需要在 blade 模板中循环遍历 Variant 的图像,因此我需要一个 collection。如何在没有 运行 太多查询的情况下将所有内容放在一起?
确保您的 Variant
模型具有这些关系:
public function product()
{
return $this->belongsTo(Product::class);
}
public function images()
{
return $this->hasMany(Image::class);
}
那么你可以这样做:
$collection = Variant::with('product', 'images')
->where('type', 'OPT')
->where('private', false)
->get();
我有三个模型,数据如下:
产品
- id
- 名字
- 描述
变体
- id
- 颜色
- 类型
- 私人
- product_id
图片
- url
- variant_id
所以关系是:
- 产品有许多变体
- 变体有许多图片
我需要获得所有变体的 collection,包括 parent 产品,因为我还需要它的名称并包括与变体相关的图像,以及条件(在变体上) ->where('type', 'OPT') 和 ->where('private', false)。
我尝试使用原始 SQL 查询来完成此操作,但我需要在 blade 模板中循环遍历 Variant 的图像,因此我需要一个 collection。如何在没有 运行 太多查询的情况下将所有内容放在一起?
确保您的 Variant
模型具有这些关系:
public function product()
{
return $this->belongsTo(Product::class);
}
public function images()
{
return $this->hasMany(Image::class);
}
那么你可以这样做:
$collection = Variant::with('product', 'images')
->where('type', 'OPT')
->where('private', false)
->get();