CakePHP: 3.1.4
I have a custom finder function in my table that gets all records from this month with the row "fee" holding a decimal value.
In a view I want to display the sum of fee values from this selection with a variable. I tried to figure it out with help of the book Using SQL Functions but I don't understand how to use the syntax correctly in my case.
Custom finder in Table:
class TicketsTable extends Table
{
// find all tickets created this month
public function findThismonths(Query $query, array $options){
// get first and last day of month
$first_day_this_month = date('m-01-Y');
$last_day_this_month = date('m-t-Y');
$query
->select(['id', 'created', 'fee', 'extend_fee'])
->where([ function($exp) {
$first_day_this_month = date('Y-m-01');
$last_day_this_month = date('Y-m-t');
return $exp->between('Tickets.created', $first_day_this_month, $last_day_this_month, 'date');
}]);
return $query;
}
I can easily get the count of records but I don't understand this works with a sum.
Controller:
class CashpositionsController extends AppController
{
public function overview()
{
$tickets = TableRegistry::get('Tickets');
$thismonths = $tickets->find('thismonths'); // get records with finder
$thismonths_count = $thismonths->count(); // get count of records
// that's what I want but this syntax does not exist in Cake...
$thismonths_sum = $thismonths->sum('fee'); // *nope*
// set to display in view
$this->set('thismonths_count', $thismonths_count);
$this->set('thismonths_sum', $thismonths_sum);
Then in the view:
<tr>
<td>Number of tickets:</td>
<td><?= $thismonths_count ?></td>
</tr>
<tr>
<td>Sum of cash:</td>
<td><?= $thismonth_sum ?></td>
</tr>
<?php foreach ($thismonths as $ticket): ?>
<tr>
<td><?= h($ticket->id) ?> </td>
<td><?= h($ticket->created) ?> </td>
<td><?= h($ticket->fee) ?></td>
</tr>
<?php endforeach; ?>
In the book there is this example:
// Results in SELECT COUNT(*) count FROM ...
$query = $articles->find();
$query->select(['count' => $query->func()->count('*')]);
But I can't get sth like this to work for me either with sum().
you can use Collection (manual)
$thismonths_sum = $thismonths->sumOf('fee');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With