kurtko
kurtko

Reputation: 2126

Get single item with particular value on hasMany relation Laravel

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.

Upvotes: 4

Views: 3637

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81157

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();

Upvotes: 3

Related Questions