CakePHP 3:如何在finder结果的列中显示值的总和
发布时间:2020-12-13 17:49:30 所属栏目:PHP教程 来源:网络整理
导读:CakePHP: 3.1.4 我在我的表中有一个自定义查找程序功能,从本月获取所有记录,行“费用”保持小数值. 在视图中,我想用变量显示此选择中的费用值之和.我试图在Using SQL Functions书的帮助下解决这个问题 但我不明白如何在我的情况下正确使用语法. 表中的自定义
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'); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |