How to get SUM on related model using eager loading, without loading whole relation data?
In my project there are two models, Account and Transaction. Account model has many transactions.
My requirement is : Get accounts and eager load only the sum on the related table.
My current code is provided : In this code transactions are eager loaded and sum is calculated using php. But I would prefer not to load the whole transactions. The only requirement is sum('amount').
table : accounts
| id | name | address | ...
table : transactions
| id | account_id | amount | ...
Account.php
/**
* Get the transaction records associated with the account.
*/
public function transactions()
{
return $this->hasMany('App\Models\Transaction', 'account_id');
}
The following code gives each accounts and its transactions.
$account = Account::with(['transactions'])->get();
SUM is calculated using :
foreach ($accounts as $key => $value) {
echo $value->transactions->sum('amount'). " <br />";
}
I have tried something like this, but didn't work.
public function transactions()
{
return $this->hasMany('App\Models\Transaction', 'account_id')->sum('amount;
}