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.
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();
;