【问题标题】:Laravel list with unique values and count of values具有唯一值和值计数的 Laravel 列表
【发布时间】:2021-04-19 12:59:19
【问题描述】:

我正在尝试在表视图中显示数据库中的唯一值以及它们的数量。但我有问题计算它们。

id | name  |
------------
 1 | john  |
 2 | john  |
 3 | smith |

我的目标是显示在表格中

name     count
---------------
john       2
smith      1

my controller

    $usersList = DB::table('users')->distinct('name')->get('name');
    
    //dd($usersList);

    return view('dashboard', compact('data'))->with(['usersList '=> $usersList]);  

dd($userList) 显示 1 john 和 1 smith

dashboard.blade

 @foreach ($usersList as $row)
       <tr>
           <th scope="row">{{ $row ->name }}</th>                            
           <td>{{ $row->count('name') }}</td>
       </tr>
 @endforeach 

error : Call to undefined method stdClass::count()

【问题讨论】:

    标签: php laravel foreach


    【解决方案1】:

    使用此代码:

    $users = User::distinct()->get(['name']);
    $users_count = [];
    foreach ($users AS $user) {
        $user_count = User::where('name', $user->name)->count('name');
        $users_count[] = $user_count;
    }
    

    在你的刀片中使用这个代码:

    @foreach ($users AS $user_key => $user_value)
        <tr>
            <th scope="row">
                {{ $user_value->name }}
            </th>                            
            <td>
                {{ $users_count[$user_key] }}
            </td>
      </tr>
    @endforeach
    

    【讨论】:

      【解决方案2】:

      在你的控制器中试试这个:

      $usersList = DB::table('users')->select(DB::raw('name as name, count(*) as 'count'  GROUP BY name'))->get();
      

      在你的 *.blade.php 文件中

          @foreach ($usersList as $row)
            <tr>
              <th scope="row">{{ $row->name }}</th>                            
              <td>{{ $row->count }}</td>
            </tr>
          @endforeach 
      

      这里是关于 DB 外观和选择的 laravel 文档:https://laravel.com/docs/4.2/queries#selects

      你可以在http://sqlfiddle.com/#!9/3b70e/1中测试这样的查询

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        相关资源
        最近更新 更多