Cakephp 3:你如何总结一个foreach循环

时间:2018-02-26 20:14:18

标签: sum cakephp-3.0

我有一个AnnualOperatingBudget表。它有很多预算费用。

 public function view($id = null)
    {
        $annualOperatingBudget = $this->AnnualOperatingBudgets->get($id, [
            'contain' => ['Azinstitutions', 
                          'BudgetExpenses', 
                          'BudgetExpenses.ExpenseTitles']
        ]);

        $this->set('annualOperatingBudget', $annualOperatingBudget );

我的view.ctp中有一个foreach循环

<td class="nonBulletList">

    <?php foreach ($annualOperatingBudget['budget_expenses'] as $expense): ?>

        <li><?= $this->Number->
                       currency($expense->expense, 'USD', ['places' => 1]) ?>
        </li>

   <?php endforeach; ?>

</td>

我需要排除所有这些费用的总和。

我尝试将此添加到我的AnnualOperatingBudgetsController:

$expenseResult = $annualOperatingBudget->select(
                   ['expense_sum' => $annualOperatingBudget->
                     func()->sum('BudgetExpenses.expense')])->
                     first(); //perform sum for the current year expenses list

$current_year_expenses = $expenseResult->expense_sum; // total sum result of Expenses

但我得到一个错误调用未定义的方法App \ Model \ Entity \ AnnualOperatingBudget :: select()

1 个答案:

答案 0 :(得分:1)

通常,您将实体功能混合在一起。获取实体返回:

 $annualOperatingBudget = $this->AnnualOperatingBudgets->get($id, [

您无法在实体上调用select,错误是试图描述:

$annualOperatingBudget->select( // This won't work

select功能适用于查询,您通常会从获取,例如:

// Returns a Query object for the AnnualOperatingBudgets table:
$query = $this->AnnualOperatingBudgets->find();

// Add the select and joins to this query
/* @var \Cake\ORM\Query $query */
$expenseResult = $query
    ->join(['BudgetExpenses'])// To sum on this table, you need to join on it too
    ->select([
        'expense_sum' => $query->func()->sum('BudgetExpenses.expense')
    ])
    ->first(); // Will return one row

另一个选择是直接在模板中汇总您输出的费用:

<?php
    $totalExpenses = 0;
    foreach ($annualOperatingBudget['budget_expenses'] as $expense) {
    $totalExpenses += $expense->expense;
?>
<li>
    <?= $this->Number->currency($expense->expense, 'USD', ['places' => 1]) ?>
</li>
<?php }; ?>
</td>
<td>
    <li>
        <?= $totalExpenses ?>
    </li>
</td>

可能想要了解一下这些: