abstract:extend目錄下面新建util目錄,SysDb.php<? phpnamespaceUtil;use think\Db; 期待的在controller中的調(diào)用方式 class SysDb extends Controller{ public function login(){ $this->db = new SysDb; $this->db->table('adm
extend目錄下面新建util目錄,SysDb.php
<? php
namespaceUtil;
use think\Db;
期待的在controller中的調(diào)用方式
class SysDb extends Controller{
public function login(){
$this->db = new SysDb;
$this->db->table('admin')->where(array('id'=>1))->item();//單條
$this->db->table('admin')->where(array('id'=>1))->lists();//多條
class SysDb{
//指定表名
public function table(){
//清空
$this->where=[];
$this->field="*";
$this->order='';
$this->limit=0;
$this->table = $table;
return $this;
}
//查詢數(shù)據(jù)字段
public function field($field = '*'){
$this->fidld=$field;
return $this;
}
//加載數(shù)量限制
public function limit($limit){
$this->limit = $limit;
return $this;
}
//排序
public function order($order){
$this->order = $order;
return $this;
}
//指定查詢條件,封裝where方法
public function where($where = []){
$this->where = $where;
return $this;
}
//查詢一條記錄,封裝一個item方法
public function item(){
return Db::name($this->table)->field($this->field)->where($this->where)->find();
}
//返回多條記錄,封裝一個lists方法
public function lists(){
$query = Db::name($this->table)->field($this->field)->where($this->where);
$this->limit && $query = $query->limit($this->limit);
$this->order && $query = $query->order($this->order);
return $query->select();
}
//封裝一個自定義方法,對索引進(jìn)行自定義
public function cates($index){
$query = Db::name($this->table)->field($this->field)->where($this->where);
$this->limit && $query = $query->limit($this->limit);
$this->order && $query = $query->order($this->order);
$lists = $query->select();
if(!$lists){
return $lists;
}
$result = [];
foreach($lists as $key => $value){
$result[$value[$index]] = $value;
}
return $result;
}
//分頁
public function pages($pageSize = 10){
$total = Db::name($this->table)->where($this->where)->count();
$query = Db::name($this->table)->field($this->field)->where($this->where);
$this->order && $query = $query->order($this->order);
$data = $query->pagenate($pageSize,$total);
return array('total'=>$total,'lists'=>$data->items(),'pages'=>$data->render());
}
//添加
public function inser($data){
return Db::name($this->table)->insertGetId($data);//會返回主鍵id
}
//批量添加數(shù)據(jù)
public function insertAll($data){
return Db::name($this->table)->insertAll($data);
}
//修改數(shù)據(jù)
public function update($data){
return Db::name($this->table)->where($this->where)->update($data);
}
}
Correcting teacher:查無此人Correction time:2019-04-16 09:45:00
Teacher's summary:完成的不錯。還可以組裝更多的操作語句,繼續(xù)加油。