0
votes

I have three models with following data:

  1. Product

    • id
    • name
    • description
  2. Variant

    • id
    • colour
    • type
    • private
    • product_id
  3. Image

    • url
    • variant_id

So the relations are:

  • Product hasMany Variants
  • Variant hasMany Images

I need to get a collection of all the Variants, including the parent Product because I also need its name and including the images related to the Variant, with the conditions (on Variant) ->where('type', 'OPT') and ->where('private', false).

I tried to do it with a raw SQL query but I need to loop through Variant's images in the blade template, so I need a collection. How can I put all together without running too many queries?

1

1 Answers

3
votes

Make sure you have these relations on your Variant model:

public function product()
{
    return $this->belongsTo(Product::class);
}

public function images()
{
    return $this->hasMany(Image::class);
}

Then you can do:

$collection = Variant::with('product', 'images')
    ->where('type', 'OPT')
    ->where('private', false)
    ->get();