[英]Eager loading the first item from multiple value from a related table in laravel 5.4
I have two tables 'purchases' and 'accounts_purchase_history'. 我有两个表“ purchases”和“ accounts_purchase_history”。 purchase has many accounts history. 购买有很多帐户历史记录。 So I need to get all the purchases with the latest history. 因此,我需要获取所有具有最新历史记录的商品。 What i have done so far 到目前为止我做了什么
$purchases = Purchases::with(['accounts_purchase_historie' => function($query){
return $query->orderBy('id','DESC')->first();
}])->orderBy('id','DESC')->where('status','extended')->get();
But this query only gets the first purchase history, How can i solve this? 但是此查询仅获取第一个购买历史记录,我该如何解决?
You can use a HasOne
relationship: 您可以使用HasOne
关系:
public function latest_history() {
return $this->hasOne(...)->orderBy('id','DESC');
}
$purchases = Purchases::with('latest_history')
->orderBy('id','DESC')
->where('status','extended')
->get();
foreach($purchases as $purchase) {
$purchase->latest_history
}
However, this will still fetch all the histories from the database in the background. 但是,这仍将在后台从数据库中获取所有历史记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.