Laravel Sum of relation

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

    class Invoices extends Eloquent {
    
        public function payments()
        {
            return $this->hasMany('Payments');
        }
    }
    
    class Payments extends Eloquent {
    
        public function invoices()
        {
            return $this->belongsTo('Invoices');
        } 
    }
    

    In your controller

    Invoice::with(['payments' => function($query){
       $query->sum('amount');
    }])->get();
    

    ;

提交回复
热议问题