如何将相关 table 的值加入到 Laravel eloquent collection?

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

我有一个 table ITEMS (sku, title) 和其他 HISTORY (sku,points,startdate)。 Table HISTORY 作为物品点数变化的历史记录。

我想在调用时加入最新的点数

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

哪种方法最好?

我知道我可以制作自定义属性,但似乎我有太多查询(因为每个项目都会进行额外的查询?)

我也可以建立关系:

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

但是有更好的方法吗? br Y

由于您只想要最新的记录,最好的选择是您显示的 hasOne 关系。这样,可以预先加载关系,因此您只调用 2 个查询,而不是 N+1 个查询。

关系:

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

用法:

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

例如:

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