Search code examples
phpmysqllaraveleloquentrelationships

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


Solution

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