首页 > 解决方案 > 如何从 foreach 循环中对刀片文件中的 linetotal 求和

问题描述

我想总结刀片文件上的标记变量。我在数据库中的表上没有行总计字段。我在总行中找到总和数量和价格,但我想总结所有行总和。

 <?php
        $sl = 1;
      ?>
    <tbody>
        @foreach($qInvoice as $sInvoice)
            <tr>
                <td>{{$sl++}}</td>
                <td>{{$sInvoice->catName}}</td>
                <td>{{$sInvoice->proName}}</td>
                <td>{{$sInvoice->qty}}</td>
                <td>{{$sInvoice->meName}}</td>
                <td class="text-right">{{$sInvoice->price}}/-</td>
                <td class="text-right">{{$sInvoice->price * $sInvoice->qty}}/-</td>

                <?php
                    $total = 0;
                    $lineTotal = $sInvoice->price * $sInvoice->qty;
                    $total+=$lineTotal;
                ?>

            </tr>
        @endforeach
    </tbody>
    <tfoot>
        <tr>
            <td colspan="5"></td>
            <td class="text-right">Total</td>
            <td class="text-right">{{$total}}/-</td>
        </tr>
    </tfoot>
    </table>

我想在不使用控制器的情况下对总字段中的所有行总计求和

标签: phplaravel

解决方案


不要在视图中求和,在控制器中进行,例如:

$qInvoice->transform(function($sInvoice) {
    $sInvoice->line_total = $sInvoice->qty * $sInvoice->price; 
    return $sInvoice;
});

$total = $qInvoice->sum($line_total);

并返回带有 $total 和 $qInvoice 的视图!


推荐阅读