gpt4 book ai didi

php - CakePHP 3 : How to display sum of values in column from finder results

转载 作者:可可西里 更新时间:2023-11-01 07:22:09 25 4
gpt4 key购买 nike

CakePHP: 3.1.4

我的表中有一个自定义查找器函数,它获取本月的所有记录,其中“费用”行包含小数值。

在一个 View 中,我想用一个变量显示这个选择的费用值的总和。我试图在书的帮助下弄明白 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;
}

我可以很容易地获得记录数,但我不明白这对总和有效。

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);

然后在 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; ?>

书中有这个例子:

// Results in SELECT COUNT(*) count FROM ...
$query = $articles->find();
$query->select(['count' => $query->func()->count('*')]);

但我无法使用 sum() 来为我工作。

最佳答案

您可以使用收藏 (manual)

$thismonths_sum = $thismonths->sumOf('fee'); 

关于php - CakePHP 3 : How to display sum of values in column from finder results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com