【问题标题】:How can I sum price on all page in the laravel?如何在 laravel 的所有页面上求和价格?
【发布时间】:2018-07-28 00:59:00
【问题描述】:

我的查询是这样的:

$orders = DB::table('orders')->paginate(10);

我的视图刀片是这样的:

@php($total = 0)
@foreach ($orders as $order)
    <tr>
        <td>{{ $order->number }}</td>
        <td>{{ $order->price }}</td>
        ....
    </tr>
    @php($total += $order->price)
@endforeach
...
Total : {!! $total !!}
{{ $orders->links() }}

从脚本中,我只在一页中得到总价

如何获取所有页面的总价?

【问题讨论】:

  • 所以你需要知道如何做一个sums 列的sql查询?
  • @lagbox 是的,我知道。但这已经设置在分页中。所以它不能总结所有
  • 是否有一些未说明的限制阻止您查询数据库以对表的列求和?
  • @lagbox 其实我的查询太复杂了。有wheregroup by等。上面的查询只是一个例子。所以我只需要使用 1 个查询
  • 你想在你的数据库价格列中求和所有价格?

标签: laravel laravel-5 foreach pagination laravel-5.6


【解决方案1】:

Laravel 视图作曲家: https://laravel.com/docs/5.6/views#view-composers

基本上,创建一个provider或者放入AppServiceProvider。

public function boot() {
    \View::composer('*', function($view) {
        $view->with('sumOrderPrice', \DB::table('orders')->sum('price'));
    });
}

\View::share('sumOrderPrice', \DB::table('orders')->sum('price'));

【讨论】:

    【解决方案2】:

    我真的建议你不要破坏 MVC 模式,所有逻辑都必须在你的控制器中完成,让控制器本身或服务来完成,但是在将所有数据传递给视图之前准备好所有数据,所以准备一个 $sum变量在你的控制器中做一个 foreach,如果不想这样做至少不要在你的视图中编写逻辑,并在你的集合实例上使用方法“sum”,看看https://laravel.com/docs/5.6/collections#method-sum,所以你的代码将变为:

    //in your controller
    $orders = DB::table('orders')->paginate(10);
    
    
    //in your view
    @foreach ($orders as $order)
        <tr>
            <td>{{ $order->number }}</td>
            <td>{{ $order->price }}</td>
            ....
        </tr>
    @endforeach
    ...
    Total : {{ $orders->getCollection()->sum('price') }}
    {{ $orders->links() }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2022-09-25
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多