具有唯一值和值计数的 Laravel 列表

时间:2021-04-19 12:59:19

标签: php laravel foreach

我正在尝试显示数据库中的唯一值,并在表视图中显示它们的数量。但我在数它们时遇到问题。

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()

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

$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

中测试这样的查询
相关问题