How can I add a sum() at the end of a table find() in cakephp 4.3

I have a table of contributions and want to add a total to the table, how can I do that?

You want to find just the sum of contributions that match your query? Or you want to get all the contribution records but also the sum of them?

I want to get all the records and the sum()

If you’re going to do something like iterate over all the records and output details from them, then building the sum as you go would be pretty straight-forward, and how I normally would handle that.

If it’s some other scenario where that doesn’t make sense, I don’t think you’ll be able to get both results from a single query. But depending on how your code is set up, you might be able to do the processing on the original query and then add a sum clause to it and re-execute to get that. If you were to share your query, people could probably help with what needs to be added to get the sum.

You have to use SQL functions.
But if you want the results AND the sum of all then you have to do two queries.

$results = $this->Contributions->find()->all()->toArray(); // or paginate or something
$query = $this->Contributions->find()->func()->sum('amount');
$total = $query->first()->toArray();
1 Like