Laravel Query Builder max函数和关系

时间:2018-09-28 21:10:22

标签: laravel

此代码

$maxsub =  Invoice::with(['userinvoicesubaccount'])->where([['person_id',$id]])->get();

 @foreach($maxsub as $max)
         {{$max->userinvoicesubaccount->subaccount_name}}   </font></div>
 @endforeach

获取与我具有预定义ID的发票清单相关的所有子帐户名称。

我需要获得的唯一与我的发票清单相关的子帐户名称金额最高 (存在于我的发票表中)且具有预定义的ID。

有什么帮助吗?谢谢

2 个答案:

答案 0 :(得分:1)

您可以将子查询添加到with函数中。

$invoices =  Invoice::with(['userinvoicesubaccount' => function($query) {
    $query->max('amount');  // Max function gives you highest value of a given column
}])
->where([['person_id', $id]])
->get();

 @foreach($invoices as $invoice)
         // You will still need to call first because you will have a collection
         {{$invoice->first()->userinvoicesubaccount->subaccount_name}}   </font></div>
 @endforeach

看看https://laravel.com/docs/5.7/eloquent-relationships#eager-loading

答案 1 :(得分:1)

首先像这样计算最高金额的发票:

$maxInvoice = Invoice::with('userinvoicesubaccount')->where('person_id',$id)
              ->orderBy('amount', 'desc')->first();

然后像这样获取该发票的相关子帐户:

$maxInvoice->userinvoicesubaccount