CakePHP: 3.1.4
我的表格中有一个自定义查找程序功能,可以获取本月的所有记录,其中“费用”行包含小数值。
在视图中,我想用变量显示此选择中的费用值之和。我试着借助这本书Using SQL Functions来解决这个问题。 但我不明白如何正确使用语法。
表中的自定义查找器:
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;
}
我可以很容易地得到记录的数量,但我不明白这是有用的。
控制器:
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);
然后在视图中:
<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; ?>
在书中有这个例子:
// Results in SELECT COUNT(*) count FROM ...
$query = $articles->find();
$query->select(['count' => $query->func()->count('*')]);
但是我不能用这样的方式(和sum())来为我工作。
答案 0 :(得分:7)
您可以使用Collection (manual)
$thismonths_sum = $thismonths->sumOf('fee');
答案 1 :(得分:0)
您可以尝试以下方式:
$totalFee = $this->find();
$totalFee->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');
}
]
);
$totalFee = $totalFee->select(['total' => $totalFee->func()->sum('fee')])->first();