问题
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 to a member function addEagerConstraints() on a non-object.
How to return the sum of all payments for each invoice in my relation?
Invoices Model:
class Invoices extends Eloquent {
public function payments()
{
return $this->hasMany('Payments')->sum('amount');
}
}
Expenses Model:
class Payments extends Eloquent {
public function invoices()
{
return $this->belongsTo('Invoices');
}
}
My table "payments" holds the foreign key of my tables invoices, which is invoices_id.
回答1:
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();
;
回答2:
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');
回答3:
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
回答4:
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');
}
回答5:
You can show this package
$invoices = Invoices::withSum('payments:amount')->get();
来源:https://stackoverflow.com/questions/31853838/laravel-sum-of-relation