4

I have two tables:

items (
    id
    name
    description
)

images (
    id
    item_id
    number     // 0 -> main image ; 1,2,3,4 ...  -> gallery_image
)

with this basic relation:

#Item.php

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

And

#Image.php

public function item()
{
    return $this->belongsTo('Item');
}

To show in my index.php all items with main image I want to get all items and the relations, but the relations only when "number" equals to "0" (main image).

If a use:

$all = $this->item->get();
foreach ($all as $one) {
        var_dump ($one->images);
}

Then I get all items (perfect) and also all images of each item. But I want a collection with all items and one image per item.

What is the best method?

Thanks.

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
kurtko
  • 1,978
  • 4
  • 30
  • 47

1 Answers1

3

The easiest way is to use 'helper' relation hasOne.

It lets you eager load that single related model:

// Use camelCase name, otherwise dynamic property won't work
public function mainImage()
{
  return $this->hasOne('Image')
    ->orderBy('number', 'asc'); 
    // or:      
    // ->where('number', 0);
}

Then you can use it and eager load it as given below:

$item->mainImage->number; // 0

$items = Item::with('mainImage')->get();
Malitta N
  • 3,384
  • 22
  • 30
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157