这次开发会员列表的时候遇到的问题首先有100个用户状态码为以下
正常:1
冻结:2
删除:0
我想要的效果是这样的
-
总数:100名 / 正常:34名 / 冻结:30名 / 删除:36名
-
这里是用户表格
// router
Route::get('member/{state?}','MemberController@browse')
->where(['state' => 'total|block|delete']);
// controller
// $state 默认是 normal
switch($state){
case 'block':$where[] = ['state','=',2];break;
case 'normal':$where[] = ['state','=',1];break;
case 'delete':$where[] = ['state','=',0];break;
}
$members = Member::where($where)->paginate(30);
但假如我要计数的话,必须得这么做么?
$count = [
'total' => Member::count(),
'block' => Member::where('state',2)->count(),
'normal' => Member::where('state',1)->count(),
'delete' => Member::where('state',0)->count(),
];
// controller
// $state 默认是 normal
switch($state){
case 'block':$where[] = ['state','=',2];break;
case 'normal':$where[] = ['state','=',1];break;
case 'delete':$where[] = ['state','=',0];break;
}
$members = Member::where($where)->paginate(30);
return view('xxx',compact('count','members'));
还是有别的方法啊?我觉得这也太原始了。我写那么多Member::where是否对数据库有负载?DEBUG里显示是这样
select * from `admins` where `id` = '1' limit 1
select count(*) as aggregate from `members`
select count(*) as aggregate from `members` where `state` = '1'
select count(*) as aggregate from `members` where `state` = '2'
select count(*) as aggregate from `members` where `state` = '0'
select count(*) as aggregate from `members` where (`state` = '0')
select * from `members` where (`state` = '0') order by `id` desc limit 30 offset 0
觉得用户列表有太多数据库请求,
这个有没有优化的方法?还是不管这些一直写下去?