Laravel Sum of relation

前端 未结 5 849
抹茶落季
抹茶落季 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:26

    This is also possible. we can do by model itself.

    class Invoices extends Eloquent {
    
        public function payments()
        {
            return $this->hasMany('Payments')
                ->selectRaw('SUM(payments.amount) as payment_amount')
                ->groupBy('id'); // as per our requirements.
            }
        }
    }
    
    

    Note SUM(payments.amount)

    payments is tableName

    amount is fieldName

提交回复
热议问题