Laravel Sum of relation

前端 未结 5 850
抹茶落季
抹茶落季 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');
    
    0 讨论(0)
  • 2021-01-27 18:21

    You can show this package

    $invoices = Invoices::withSum('payments:amount')->get();
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-27 18:30

    I found a simple way to acomplish this in here, you can use withPivot() method.

    You can redefine a bit your relation to something like following

    public function expenses()
    {
        return $this->belongsToMany('Expenses', 'invoices_expenses')
                       ->withPivot('name', 'amount', 'date');
    } 
    
    0 讨论(0)
  • 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();
    

    ;

    0 讨论(0)
提交回复
热议问题