Yuray
Yuray

Reputation: 827

How to join value from related table to Laravel eloquent collection?

I have one table ITEMS (sku, title) and other HISTORY (sku,points,startdate). Table HISTORY serves as history for item points changes.

I would like to join latest points when calling

$items = \App\Items::all();

Which is best way to do it?

I know i can make custom attribute, but it seems that then i have too many queries (since for each item it will make aditional query?)

Also i can make relation:

public function points()
    {
        return $this->hasOne('App\History','sku','sku')->orderBy('startdate','DESC');
    }

But is there better way? br Y

Upvotes: 0

Views: 1676

Answers (2)

Illia Yaremchuk
Illia Yaremchuk

Reputation: 2025

For example:

 class Items extends Model
{
    protected $primaryKey = 'sku';

    public function points()
    {
         return $this->hasOne('App\History','sku','sku')->orderBy('startdate','DESC');
    }


    public function getItems(){
         $items = \App\Items::with('points')->get();
    }
}

Upvotes: 0

patricus
patricus

Reputation: 62248

Since you only want the latest record, the best option is the hasOne relationship you've shown. That way, the relationship can be eager loaded, so you're only calling 2 queries, instead of N+1 queries.

Relationship:

public function currentPoints()
{
    return $this->hasOne('App\History','sku','sku')->orderBy('startdate','DESC');
}

Usage:

$items = \App\Items::with('currentPoints')->get();

Upvotes: 2

Related Questions