【问题标题】:Display total amount for a charity in Laravel 5.2在 Laravel 5.2 中显示慈善机构的总金额
【发布时间】:2016-11-20 12:06:42
【问题描述】:

我有一个charity_donations 表,其中包含一个charity_id、为该慈善机构捐赠的金额以及其他字段。这就是它的外观。

我需要做的是,我需要按每个慈善机构 ID 进行分组,然后计算为该特定慈善机构捐赠的金额。最重要的是,我需要在视图中显示它。

类似这样的事情:

慈善ID |总计

1 | 1,200 美元 ....

我试过了,

 $displayPerCharity = CharityDonation::select(DB::Raw('charity_id, COUNT(*) as              count'))->groupBy('charity_id')->get();

        dd($displayPerCharity);

计算慈善机构 ID,然后为我提供每个慈善机构的总数。但我需要每个慈善机构的总金额,然后显示在视图中。

【问题讨论】:

    标签: php group-by laravel-5.2


    【解决方案1】:

    知道了!

    $displayPerCharity = DB::table('charity_donations')
                ->select(DB::raw('SUM(amount) as charity_amount, charity_id'))
                ->groupBy('charity_id')
                ->orderBy('charity_amount', 'desc')
                ->get();
    

    然后在视图中:

    @foreach ($displayPerCharity as $group)
      <h1> Charity ID {{ $group->charity_id }} received {{ $group->charity_amount }}</h1>
    @endforeach
    

    【讨论】:

      【解决方案2】:

      您如何显示它完全取决于您希望它的外观。

      如果您只是纠结于如何获取每个慈善机构 ID 和金额,那么您只需使用 foreach 循环即可。

      这是一个使用 Bootstrap 响应式表格的示例。这假定在您运行查询后,您已将其作为名为 $displayPerCharity 的变量传递给视图。

      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th>Charity ID</th>
              <th>Amount ($)</th>
            </tr>
          </thead>
          <tbody>
            @foreach($displayPerCharity as $display)
            <tr>
              <td>{{ $display->charity_id }}</td>
              <td>{{ $display->charity_amount }}</td>
            </tr>
            @endforeach
          </tbody>
        </table>
       </div>
      

      【讨论】:

      • 是的,这行得通。谢谢!我以为那会更复杂。大声笑
      猜你喜欢
      • 2017-06-09
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2021-03-26
      相关资源
      最近更新 更多