????:<?php namespace app\admin\controller; use app\admin\model\UserModel; use think\Controller; use think\facade\Request; class User extends Controller{ &
<?php namespace app\admin\controller; use app\admin\model\UserModel; use think\Controller; use think\facade\Request; class User extends Controller{ //渲染管理員界面 public function index(){ //查詢操作 $user = new UserModel(); $users = $user->order('id','DESC')->paginate(8); //查詢后,將數(shù)據(jù)賦值給模板 $this->view->users = $users; //渲染管理員頁面 return $this->fetch(); } //渲染添加管理員界面 public function add(){ return $this->fetch(); } public function DoAdd(){ //獲取前臺提交來的數(shù)據(jù) $data = Request::param(); $data['time'] = time(); $username = $data['username']; //使用用戶名這個變量來看看數(shù)據(jù)庫中是否有對應(yīng)的數(shù)據(jù) $res = UserModel::where('username',$username)->find(); if($res == true){ return['res'=>0,'msg'=>'用戶名已存在!']; } $user = new UserModel(); //將數(shù)據(jù)庫傳入數(shù)據(jù)庫并驗(yàn)證 if($user->save($data)){ return['res'=>1,'msg'=>'添加成功!']; }else{ return['res'=>0,'msg'=>'添加失??!']; } } //對管理員進(jìn)行編輯操作 之 渲染編輯框 public function edit(){ //獲取前臺提交過來的數(shù)據(jù) $userId = Request::param('id'); //通過用戶id查詢需要更新用戶的所有數(shù)據(jù).user是模板變量 $user = UserModel::get($userId); //將數(shù)據(jù)賦值給模板 $this->view->user = $user; //渲染編輯頁面 return $this->fetch(); } //對管理員進(jìn)行編輯操作 之 提交數(shù)據(jù) //DoEdit在html文檔中成為了jQ方法中的提交地址 public function DoEdit(){ $data = Request::param(); $user = new UserModel(); //對數(shù)據(jù)庫中的數(shù)據(jù)進(jìn)行修改更新 $res = $user->save([//save內(nèi)部指定修改什么數(shù)據(jù) 'username'=>$data['username'], 'time'=>time(), ],['id'=>$data['id']] //后面的這個是條件,將提交過來的id在數(shù)據(jù)庫中進(jìn)行查找 ); //判斷是否修改成功 if($res){ return['res'=>1,'msg'=>'修改成功!']; } } //刪除管理員 public function del(){ //獲取需要刪除的管理員Id $userId=Request::param('id'); $user = new UserModel(); //進(jìn)行刪除并驗(yàn)證操作 if($user->destroy($userId)){ return['res'=>1,'msg'=>'刪除成功!']; } } }
//對應(yīng)模板代碼如下
<?php namespace app\admin\model; use \think\Model; class UserModel extends Model { protected $table = 'user'; protected $pk = 'id'; }
?? ???:天蓬老師?? ??:2019-04-12 09:18:33
???? ??:以后再寫這類代碼的時候,可以按一定的套路走, 事先可以寫一個大綱