摘要:<?php /** * Created by PhpStorm. * User: Jason * Date: 2019/4/29 * Time: 7:25 */ namespace Util; use think\Db;
<?php /** * Created by PhpStorm. * User: Jason * Date: 2019/4/29 * Time: 7:25 */ namespace Util; use think\Db; // 數(shù)據(jù)庫(kù)操作類 class SysDb { // 是否建立連接標(biāo)志 public static $instance = null; // 封裝靜態(tài)方法調(diào)用 public static function getnstance($table) { // 如果連接為空,則創(chuàng)建連接 好像這樣有問題 //if(self::$instance == null) { //self::$instance = self::table($table); //} //return self::$instance; // 靜態(tài)方法調(diào)用,不需要實(shí)例化 return self::table($table); } // 表名 public function table($table) { // 清空數(shù)據(jù) $this->where = []; $this->field = '*'; $this->order = ''; $this->limit = 0; $this->table = $table; return $this; } // 查詢字段 public function field($field = '*') { $this->field = $field; return $this; } // 指定查詢數(shù)量 public function limit($limit) { $this->limit = $limit; return $this; } // 數(shù)據(jù)排序 public function order($order) { $this->order =$order; return $this; } // 條件 public function where($where = []) { $this->where = $where; return $this; } // 返回一條記錄 public function item(){ return Db::name($this->table)->field($this->field)->where($this->where)->find(); } // 返回多條記錄 public function lists() { $query = Db::name($this->table)->field($this->field)->where($this->where); // 如果有l(wèi)imit 并查詢 $this->limit && $query = $query->limit($this->limit); // 如果有排序并查詢 $this->order && $query = $query->order($this->order); // 返回?cái)?shù)據(jù)集合 return $query->select(); } // 自定義索引 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(); // 如果沒有查詢到數(shù)據(jù),直接返回 if(!$lists){ return $lists; } // 定義結(jié)果集 $result = []; foreach($lists as $value) { $result[$value[$index]] = $value; } // 返回按字段索引查詢的結(jié)果集 return $result; } // 分頁(yè)方法 public function pages($pageSize = 10) { // 查詢數(shù)據(jù)總數(shù) $total = Db::name($this->table)->where($this->where)->count(); // 查詢數(shù)據(jù) $query = Db::name($this->table)->field($this->field)->where($this->where); // 如果有排序,就進(jìn)行排序查詢 $this->order && $query = $query->order($this->order); // 查詢分頁(yè) 查詢數(shù)量,數(shù)據(jù)總數(shù) $data = $query->paginate($pageSize,$total); // 返回自定義集合 return ['total'=>$total,'lists'=>$data->items(),'pages'=>$data->render()]; } // 單條數(shù)據(jù)寫入 public function insert($data) { // 寫入并返回主鍵ID return Db::name($this->table)->insertGetId($data); } // 批量插入數(shù)據(jù) public function insertAll($data) { // 批量寫入 return Db::name($this->table)->insertAll($data); } // 更新數(shù)據(jù) public function update($data) { // 更新并返回?cái)?shù)據(jù) return Db::name($this->table)->where($this->where)->update($data); } }
批改老師:天蓬老師批改時(shí)間:2019-04-29 09:12:35
老師總結(jié):用單例模式創(chuàng)建數(shù)據(jù)庫(kù)連接, 是很不錯(cuò)的主意, 也是常用的技巧