0

I have three Models:

Car.php, Colour.php, Image.php.

They have the following relationships:

Car belongsToMany Colour: Because a car can have multiple colours.

Colour belongsToMany Car: Because a colour can appear on many cars.

Car belongsToMany Image: Because a car can have multiple images.

Image belongsToMany Car: Because one image can be used by multiple Cars.

Image belongsTo Colour: Because every image must have a colour.

Colour hasMany Image: Because the colour Red can be found in many images.

If I write Car::find(1)->load('colours.images); it returns all associated colours as expected, however each colour has every image that uses that colour. So I'll see Car 1, 2, 3 etc for Red instead of just the images for car 1.

It seems like the colours.images ignores the initial car.

What am I doing wrong?

2 Answers2

0

Try something like Car::find($id)->with(['colours.images' => function ($query) { $query->where('car_id', $id); }])

ge022
  • 134
  • 1
  • 7
0

What you need is HasManyThrough relation, but the problem is that your cars, colors and images are in many-to-many relationship (hasManyThrough only works with one-to-many relationship nesting).

Check this answer for more info and possible workaround.

d3jn
  • 1,392
  • 3
  • 13
  • 21