如何解决具有唯一值和值计数的 Laravel 列表
我正在尝试显示数据库中的唯一值,并在表视图中显示它们的数量。但我在数它们时遇到问题。
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()
解决方法
使用此代码:
$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
,
在你的控制器中试试这个:
$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
中测试这样的查询版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。