It is making a subquery so no. It isnt possible. You would need to do the * 100 afterwards
Feb 20, 2023
9
Level 63
withSum doesn't take into account the accessor
Hello,
In the Transaction model, I have an accessor.
protected function amount(): Attribute
{
return Attribute::make(
get: fn (?int $value) => $value ? floatval($value) / 100 : null,
set: fn (float $value) => intval($value * 100),
);
}
And I'd like to retrieve the sum of the amounts with this code.
$accounts = Account::
withSum('transactions', 'amount')
->orderBy('name')
->get();
The problem is that withSum seems to retrieve the amounts directly from the datase, so it doesn't retrieve the amounts divided by 100.
Is it possible to force the query to pass by the accessor ?
How is it possible to solve this problem ?
Thanks for your help.
V
Level 102
@vincent15000 You could perhaps do two withSums then ?
$accounts = Account::query()
->withSum(['transactions as transactions_income_sum_amount' => function($query) [
$query->where('income', true);
}, 'transactions as transactions_expense_sum_amount' => function($query) [
$query->where('income', false);
}], 'amount')
->orderBy('name')
->get()
->map(function($account) {
$account->transactions_income_sum_amount = $account->transactions_income_sum_amount / 100;
$account->transactions_expense_sum_amount = $account->transactions_expense_sum_amount / 100;
return $account;
});
1 like
Please or to participate in this conversation.