我有两个表“purchases”和“accounts_purchase_history”。购买有许多帐户历史记录。所以我需要获取所有具有最新历史记录的购买记录。 到目前为止我做了什么
$purchases = Purchases::with(['accounts_purchase_historie' => function($query){
return $query->orderBy('id','DESC')->first();
}])->orderBy('id','DESC')->where('status','extended')->get();
但是这个查询只能获取第一次购买历史记录,我该如何解决这个问题?
最佳答案
您可以使用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
}
但是,这仍然会在后台从数据库中获取所有历史记录。
关于php - 渴望从 Laravel 5.4 中的相关表中的多个值加载第一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436496/