繁体   English   中英

CakePHP 3:如何在finder结果的列中显示值的总和

[英]CakePHP 3: How to display sum of values in column from finder results

CakePHP: 3.1.4

我在我的表中有一个自定义查找程序功能,从本月获取所有记录,行“费用”保持小数值。

在视图中,我想用变量显示此选择中的费用值之和。 我试图在“ 使用SQL函数 ”一书的帮助下解决这个问题,但我不明白如何在我的案例中正确使用语法。

表中的自定义查找器:

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 (手册)

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

您可以尝试以下方式:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM