首页 > 解决方案 > Laravel,尝试使用数据库中的值进行计数

问题描述

我需要一些关于 Laravel 的帮助,我正在尝试使用我的数据库中的信息和计数来做一个列表,例如: 列表图像

如何计算同一地点在我的列表中出现的次数?记住:我的地点列表来自我的数据库,地点是可变的。我数不过来。这是我的代码:

<table border=`1px` class="table-teste">
    <tr>
        <td><h3> Place</h3></td>
        <td><h3> Count</h3></td>
    </tr>
    @foreach ($setor_data as $setor)
        <tr>
            <td>{{$setor->setor}}</td>
        </tr>
    @endforeach
</table>

我的控制器:

  $setor_data = DB::table('atividades')
      ->where('local', $condominio)
      ->whereDate('date', '>=', $dtinicio)
      ->whereDate('date','<=',$dtok)
      ->orderBy("setor")
      ->select('setor')
      ->get();

标签: laravel

解决方案


用户 groupBy 来计算查询中列表中的每个项目,如下所示:

$setor_data = DB::table('atividades')
               ->where('local', $condominio)
               ->whereDate('date', '>=', $dtinicio)
               ->whereDate('date','<=',$dtok)
               ->orderBy("setor")
               ->select('setor', , DB::raw('count(*) as total'))
               ->get();

然后在刀片视图中:

@foreach ($setor_data as $setor)
   <tr>
      <td>{{$setor->setor}}</td>
      <td>{{$setor->total}}</td>
   </tr>
@endforeach

希望能帮助到你...


推荐阅读