简体   繁体   English

Laravel-刀片中的数学计算

[英]Laravel - Math computations in blades

Is it possible to add two integers from the database inside a blade? 是否可以在刀片内的数据库中添加两个整数?

To give a scenario, I have a controller that compacts a collection of orders table. 给一个场景,我有一个控制器,它压缩了orders表的集合。

$solditems =  DB::table('orders')
            ->where('status', 'served')
            ->orderBy('id')
            ->get();

        return view('salesreports.sellingitems.index', compact('solditems'));

And I used those like this in my blade. 我在刀片中使用了这样的工具。

                <table class="table table-hover">
                    <tr>
                        <th>ID</th>
                        <th>Item</th>
                        <th>Sales</th>
                    </tr>
                <thead>
                </thead>
                    <tbody>
                        @forelse($solditems as $solditem) 
                            <tr>
                                <td>{{$solditem->id}}</td>
                                <td>{{$solditem->item}}</td>
                                <td>{{$solditem->subtotal}}</td>
                            </tr>
                        @empty
                        @endforelse
                    </tbody>
                </table>

Now, what I want to do is to combine an item that has same item names or $solditem->item while adding up there subtotals. 现在,我想做的是合并一个具有相同项目名称或$solditem->item同时将这些$solditem->item汇总在一起。

For example; 例如;

ID #1 Apple = 50
ID #2 Apple = 80

Will become this; 将成为这个;

ID #1 Apple = 130

I tried using groupBy on query builder so an item with same name will only show once, but I'm having problems designing an algorithm adding up the subtotal. 我尝试在查询生成器上使用groupBy,因此具有相同名称的项目仅显示一次,但是在设计将小计加起来的算法时遇到了问题。

Try this one, This gives you sum of cost with same item name for all items. 试试这个,这将为您提供所有项目具有相同项目名称的成本总和。

$solditems =  DB::table('orders')
              ->where('status', 'served')
              ->select('orders.*',DB::raw('SUM() as total'))
              ->groupBy('orders.item')
              ->orderBy('id')
              ->get();

You could take advantage of Laravel's collection methods. 您可以利用Laravel的收集方法。 You can use the GroupBy method to create grouped subarrays by product name and foreach of those group using the Sum method return the sum of the total column. 您可以使用GroupBy方法按产品名称创建分组的子数组,并使用Sum方法对这些组的每一个返回总列的总和。

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

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