Laravel Sum of relation

前端 未结 5 900
抹茶落季
抹茶落季 2021-01-27 18:07

I want to return the sum of \"amount\" from my payments table. There can be many payments for one invoice. The below \"->sum(\'amount\') does not work, it returns:

Call

5条回答
  •  误落风尘
    2021-01-27 18:13

    First decide which Invoice (for example id 1)

    $invoice = Invoices::find(1);
    

    Then eager load all the corresponding payments

    $eagerload = $invoice->payments;
    

    Finally assuming you have the amount field in your Invoice model you can simply find the sum using the method below:

    $totalsum = $eagerload->sum('amount');
    

提交回复
热议问题