亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

嵌套模板完成的增刪改查

原創(chuàng) 2019-05-29 23:10:00 245
摘要:<?php namespace app\admin\controller; use app\admin\model\UserModel; use think\Controller; use think\facade\Request; //獲取請(qǐng)求的; class User extends Controller { /
<?php
namespace app\admin\controller;

use app\admin\model\UserModel;
use think\Controller;
use think\facade\Request;	//獲取請(qǐng)求的;

class User extends Controller
{
	//查詢;
	public function index(){
		//查詢構(gòu)造器方法;
		$users = UserModel::all(function($query){
			$query->field('*')->paginate(1);
		});
		$this->view->assign('users',$users);
		return $this->fetch();
	}

	//顯示添加頁(yè)面;
	public function add(){
		return $this->fetch();
	}

	//處理添加數(shù)據(jù);
	public function DoAdd(){
		//獲取前臺(tái)提交過(guò)來(lái)的數(shù)據(jù);
		$data = Request::param();
		//獲取添加的時(shí)間;
		$data['time'] = time();
		$username = $data['username'];
			//通過(guò)model函數(shù)在數(shù)據(jù)庫(kù)中匹配username;
		$res = UserModel::where('username',$username)->find();
		if($res){
			return['code'=>0,'msg'=>'用戶已存在'];
		}
		//實(shí)例化UserModel類(lèi),需要use引入;
		$user = new UserModel();
		if($user->save($data)){
			return['code'=>1,'msg'=>'添加成功'];
		}else{
			return['code'=>0,'msg'=>'添加失敗'];
		}

	}

	//顯示編輯頁(yè)面;
	public function edit(){
		////獲取前臺(tái)提交過(guò)來(lái)的數(shù)據(jù);有參數(shù)就獲取這個(gè)參數(shù);
		$userId = Request::param('id');
		//在模板中查找這個(gè)id;
		$user = UserModel::get($userId);
		//根據(jù)id查找到的數(shù)據(jù)顯示在編輯頁(yè)面;模板賦值;
		$this->view->assign('user',$user);
		//模板渲染;
		return $this->fetch();
	}


	// 處理編輯數(shù)據(jù);
	public function doEdit(){
		//請(qǐng)求獲取所有數(shù)據(jù);
		$data = Request::param();
		$user = new UserModel();
		$res = $user->save(
			['username'=>$data['username'],'time'=>time()],
			['id'=>$data['id']]
		);
		if($res){
			return['code'=>1,'msg'=>'修改成功'];
		}
		
	}

	//刪除;
	public function del(){
		//請(qǐng)求需要?jiǎng)h除的id;
		$userId = Request::param('id');
		//實(shí)例化model
		$user = new UserModel();
		//通過(guò)模塊來(lái)操作數(shù)據(jù)庫(kù);
		$res = $user->destroy($userId);
		//判斷是否刪除?
		if($res){
			return['code'=>1,'msg'=>'刪除成功'];
		}else{
			return['code'=>0,'msg'=>'刪除失敗'];
		}
	}


}


批改老師:天蓬老師批改時(shí)間:2019-05-30 15:59:31
老師總結(jié):一個(gè)方法或函數(shù)中, 多次出現(xiàn)return 是一種不太規(guī)范的編程方式, return 應(yīng)該只出現(xiàn) 一次: if($res){ return['code'=>1,'msg'=>'刪除成功']; }else{ return['code'=>0,'msg'=>'刪除失敗']; } 像這種情況, 完全可以創(chuàng)建一個(gè)臨時(shí)變量來(lái)解決

發(fā)佈手記

熱門(mén)詞條