CakePHP: 3.1.4
I have a custom finder function in my table that gets all records from this month with the string "fee" with a decimal value.
In the view, I want to display the sum of the reward values from this selection with a variable. I tried to figure this out with the book Using SQL Functions,
but I don’t understand how to use the syntax correctly in my case.
Custom table search:
class TicketsTable extends Table
{
public function findThismonths(Query $query, array $options){
$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 number of records, but I do not understand that this works with the sum.
Controller:
class CashpositionsController extends AppController
{
public function overview()
{
$tickets = TableRegistry::get('Tickets');
$thismonths = $tickets->find('thismonths');
$thismonths_count = $thismonths->count();
$thismonths_sum = $thismonths->sum('fee');
$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; ?>
The book gives an example:
$query = $articles->find();
$query->select(['count' => $query->func()->count('*')]);
But I can't get this to work for me either with sum ().