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()来为我工作.
解决方法
你可以使用Collection
(manual)
$thismonths_sum = $thismonths->sumOf('fee');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。