Correction status:Uncorrected
Teacher's comments:
在laravel中使用数据库查询DB::table(‘admin’)->get()->toArray();会生成数组下的对象,既有数组又有对象,在使用中比较麻烦、容易出错。因此需要对数据库访问类进行扩展,在laravel7\app\Providers下生成DBServiceProvider.php,在Admin.php中就可以使用lists()方法。生成的数据为二维数组。
注:并不是所有类都可扩展,macroable的才可扩展。
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder as QueryBuilder;
class DBServiceProvider extends ServiceProvider
{
public function boot()
{
//
QueryBuilder::macro('lists',function(){
$data = $this->get()->toArray();
$result = [];
foreach($data as $val){
$result[] = (array)$val;
}
return $result;
});
}
}
```Admin.php
###
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
// 管理员管理
class Admin extends Controller
{
// 账号列表
public function index(){
$data['admins'] = DB::table('admin')->lists();
foreach($data['admins'] as $key => $val) {
$group = DB::table('admin_group')->where('gid',$val['gid'])->first();
$data['admins'][$key]['group_title'] = $group->title;
}
/*
$data['admins'] = DB::table('admin')->get()->toArray();
foreach($data['admins'] as $key => $val) {
$group = DB::table('admin_group')->where('gid',$val->gid)->first();
$data['admins'][$key]->group_title = $group->title;
}
*/
return view('admins/admin/index',$data);
}
}
<!DOCTYPE html>
<html>
<head>
<title>账号列表</title>
<link rel="stylesheet" type="text/css" href="/static/plugins/layui/css/layui.css">
<script type="text/javascript" src="/static/plugins/layui/layui.js"></script>
<style>
</style>
</head>
<body style="padding: 10px;">
<table class="layui-table">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>分组</th>
<th>真实姓名</th>
<th>最后登录时间</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
@foreach($admins as $admin)
<tr>
<td>{{$admin['id']}}</td>
<td>{{$admin['username']}}</td>
<td>{{$admin['group_title']}}</td>
<td>{{$admin['real_name']}}</td>
<td>{{$admin['lastlogin']?date('Y-m-d H:i:s',$admin['lastlogin']):''}}</td>
<td>{{$admin['status']==0?'正常':'禁用'}}</td>
<td>
<button class="layui-btn layui-btn-xs">修改</button>
<button class="layui-btn layui-btn-danger layui-btn-xs">删除</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>