Codeigniter4通用自定義數據庫操作類

 

CI4框架封裝了一些方法,方便對數據庫的操作和使用

  1. 單條/多條記錄:獲取、更新、插入、假刪除、記錄操作log 等
  2. 自動更新時間戳、排序更改、分頁獲取、樹狀獲取、直接執行sql等
  3. 假定了數據庫有指定的字段(如更新時間等),有日誌表(消耗很大),內容附後
  4. 基本用法是每個需要用到操作數據庫的model文件,都繼承此文件,並在實例化後調用方法就可以了。參數基本可以做到望文生義,可以自己琢磨,不懂的留言
  5. 用法:控制器+模型+自定義數據庫操作類(重點)+數據表標準(重點)
  6. 控制器
  7. <?php
    //控制器
    namespace App\Controllers\MyTestController;
    use App\Models\Role_model;
    class MyTestController extends Api_apps_logged {
    	function __construct() {
    		$this->model_name = 'Jingkaiqu\Investigate_record_model';
    		parent::__construct();
    	}
    function myTestFunction (){
    			$this->Role_model= new Role_model();
    			$record = $this->Role_model->db_row($table_name = '', $id = 1, $where = array(), $order_by = null, $sort = 'desc', $include_delete = false);
        }
    		
    }
    ?>
    
  8.  模型
  9. <?php   
    //模型
    namespace App\Models;
    use CodeIgniter\Model;
    
    class Role_model extends Base_model {//繼承自定義數據庫操作類
    	public function __construct() {
    		$this->table_name = 'role';
    		parent::__construct();
    	}
    }
    ?>
    

     

  10. 自定義數據庫操作類
  11. <?php
    
    namespace App\Models;
    use CodeIgniter\Model;
    //use \Symfony\Component\VarDumper\Test\VarDumperTestTrait;
    
    class Base_model extends Model{
    	/* 此類中操作數據庫的方法
    	  1:如無特殊情況,獲取數據時不獲取有deleted_at時間的數據
    	  2:其中的更新db_update_row 和 db_update_batch方法,使用時會嘗試更新記錄中的updated_at字段
    	 * 3:推薦對應每張表新建一個模型文件
    	 *  */
    
    	function __construct() {
    		parent::__construct();
    	}
    
    	public function setDatabase($databaseName) {
    		$this->db = \Config\Database::connect($databaseName);
    	}
    
    	/* 優先使用傳入的表名。如沒有則使用model文件中定義的默認表名
    	 * 推薦對應每張表新建一個模型文件
    	 */
    
    	public function default_table_name($table_name = '') {
    		$table_name = trim($table_name);
    		$table_name = !empty($table_name) ? $table_name : $this->table_name;
    		return $table_name;
    	}
    
    	/* 獲取數量
    	 * @return db_count
    	 */
    
    	public function db_count($table_name = '', $where = array()) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		$this->dbSource->select('COUNT(*) AS num');
    		if (!isset($where['deleted_at']) || strtolower($where['deleted_at']) == 'null') {
    			$this->dbSource->where('deleted_at', null);
    		} else {
    			unset($where['deleted_at']);
    		}
    		$this->dbSource->where('display', 1);
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		$query = $this->dbSource->get();
    		if ($query->resultID->num_rows > 0) {
    			$getRowArray = $query->getRowArray();
    			return $getRowArray['num'];
    		} else {
    			return null;
    		}
    	}
    	//返回單條記錄
    	public function db_row($table_name = '', $id = '', $where = array(), $order_by = null, $sort = 'desc', $include_delete = false, $select = '*', $include_display = false, $where_in = array()) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		$this->dbSource->select($select);
    		if ($id != '') {
    			$this->dbSource->where('id', intval($id));
    		}
    		if (!$include_delete) {
    			$this->dbSource->where('deleted_at', null);
    		}
    		if (!$include_display) {
    			$this->dbSource->where('display', 1);
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($order_by)) {
    			$this->dbSource->orderBy($order_by, $sort);
    		}
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    		$query = $this->dbSource->get();
    
    		if ($query->resultID->num_rows > 0) {
    			return $query->getRowArray();
    		} else {
    			return null;
    		}
    	}
    	//必須選定select返回單條記錄
    	public function db_row_colum($select, $table_name = '', $id = '', $where = array(), $order_by = null, $sort = 'desc', $include_delete = false) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		$this->dbSource->select($select);
    		if (intval($id)) {
    			$this->dbSource->where('id', intval($id));
    		}
    		if (!$include_delete) {
    			$this->dbSource->where('deleted_at', null);
    		}
    		$this->dbSource->where('display', 1);
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($order_by)) {
    			$this->dbSource->orderBy($order_by, $sort);
    		}
    		$query = $this->dbSource->get();
    		if ($query->resultID->num_rows > 0) {
    			return $query->getRowArray();
    		} else {
    			return null;
    		}
    	}
    
    	/* 執行sql字符串
    	 * $return  [rowArray,getResultArray]對應返回單條/多條
    	 */
    
    	public function db_query_sql($sql, $return = 'getResultArray') {
    		$query = $this->db->query($sql);
    		if ($return === 'bool') {
    			if($query->resultID !== true && $query->resultID !== false && $query->resultID !== null && isset($query->resultID->num_rows) ){
    				if($query->resultID->num_rows > 0){
    					$return = true;
    				}else{
    					$return = false;
    				}
    			}else{
    				$return = $query->resultID;
    			}
    			return $return;
    		} else {
    			if ($query) {
    				switch ($return) {
    					case 'getResultArray':
    						$return = $query->getResultArray();
    						break;
    					case 'rowArray':
    						$return = $query->getRowArray();
    						break;
    					default:
    						return false;
    				}
    				return $return;
    			} else {
    				return null;
    			}
    		}
    	}
    
    	/* 獲取多條記錄,可指定分頁
    	 * $page = null, $num = null 傳入指定參數設置分頁
    	 * @return multiple array
    	 * $where_in = array();
    	 * $where_in['id'] = explode(',', $announcement['area_group_ids']);
    	 */
    
    	public function db_array($table_name = '', $page = null, $num = null, $where = array(), $where_in = array(), $like = array(), $or_like = array(), $timeRange = array(), $order_by = null, $sort = 'desc', $or_where = array()) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		$this->dbSource->select('*');
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    		if (!empty($or_like)) {
    			$this->dbSource->groupStart();
    			$this->dbSource->orLike($or_like);
    			$this->dbSource->groupEnd();
    		}
    		if (!empty($order_by) && !empty($sort)) {
    			$this->dbSource->orderBy($order_by, $sort);
    		}
    		if (!empty($or_where)) {
    			$this->dbSource->groupStart();
    			foreach ($or_where as $o_key => $o_value) {
    				if (is_array($o_value) && count($o_value) == 3 && isset($o_value['field']) && isset($o_value['value']) && isset($o_value['escape'])) {
    					$this->dbSource->orWhere($o_value['field'], $o_value['value'], $o_value['escape']);
    				}
    			}
    			$this->dbSource->groupEnd();
    		}
    		if (!empty($timeRange)) {
    			if (isset($timeRange['timeRangeStyle'])) {
    				$timeRangeStyle = intval($timeRange['timeRangeStyle']);
    				if ($timeRangeStyle === 1) {
    					if (isset($timeRange['start']) && $timeRange['start']) {
    						$this->dbSource->where('created_at >=', $timeRange['start']);
    					}
    					if (isset($timeRange['end']) && $timeRange['end']) {
    						$this->dbSource->where('created_at <=', $timeRange['end']);
    					}
    				} else if ($timeRangeStyle === 2) {
    					$this->dbSource->where('created_at IS NULL');
    				}
    			}
    		}
    		$this->dbSource->where('deleted_at', null);
    		$this->dbSource->where('display', 1);
    
    		if ($page != null && $num != null) {
    			$offset = ($page - 1) * $num;
    			$this->dbSource->limit($num, $offset);
    		}
    		$query = $this->dbSource->get();
    		if ($query->resultID->num_rows > 0) {
    			$return = $query->getResultArray();
    			return $return;
    		} else {
    			return null;
    		}
    	}
    
    	/* 按條件獲取表內數據(無論有無deleted_at數據)
    	 * 返回數組
    	 *  @return multiple array
    	 */
    
    	public function db_all_include_deleted($table_name, $where, $or_like, $timeRange, $order_by, $sort) {
    		$order_by = $order_by === null ? 'created_at' : $order_by;
    		$sort = $sort === null ? 'DESC' : $sort;
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		/* 獲取數據 */
    		$this->dbSource->select('*');
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($or_like)) {
    			$this->dbSource->groupStart();
    			$this->dbSource->orLike($or_like);
    			$this->dbSource->groupEnd();
    		}
    
    		if (!empty($timeRange)) {
    			if (isset($timeRange['timeRangeStyle'])) {
    				$timeRangeStyle = intval($timeRange['timeRangeStyle']);
    				if ($timeRangeStyle === 1) {
    					if (isset($timeRange['start']) && $timeRange['start']) {
    						$this->dbSource->where('created_at >=', $timeRange['start']);
    					}
    					if (isset($timeRange['end']) && $timeRange['end']) {
    						$this->dbSource->where('created_at <=', $timeRange['end']);
    					}
    				} else if ($timeRangeStyle === 2) {
    					$this->dbSource->where('created_at IS NULL');
    				}
    			}
    		}
    		$this->dbSource->orderBy($order_by, $sort);
    		$query = $this->dbSource->get();
    		if ($query->resultID->num_rows > 0) {
    			$result = $query->getResultArray();
    			return $result;
    		} else {
    			return null;
    		}
    	}
    
    	/* 按條件獲取表內數據(不包含deleted_at時間數據)
    	 * 返回數組
    	 *  @return multiple array
    	 */
    
    	public function db_all_data($table_name = '', $where = array(), $where_in = array(), $or_like = array(), $timeRange = array(), $order_by = 'sort', $sort = 'desc') {
    		$order_by = $order_by === null ? 'created_at' : $order_by;
    		$sort = $sort === null ? 'DESC' : $sort;
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		/* 獲取數據 */
    		$this->dbSource->select('*');
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($or_like)) {
    			$this->dbSource->groupStart();
    			$this->dbSource->orLike($or_like);
    			$this->dbSource->groupEnd();
    		}
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    
    		if (!empty($timeRange)) {
    			if (isset($timeRange['timeRangeStyle'])) {
    				$timeRangeStyle = intval($timeRange['timeRangeStyle']);
    				if ($timeRangeStyle === 1) {
    					if (isset($timeRange['start']) && $timeRange['start']) {
    						$this->dbSource->where('created_at >=', $timeRange['start']);
    					}
    					if (isset($timeRange['end']) && $timeRange['end']) {
    						$this->dbSource->where('created_at <=', $timeRange['end']);
    					}
    				} else if ($timeRangeStyle === 2) {
    					$this->dbSource->where('created_at IS NULL');
    				}
    			}
    		}
    		$this->dbSource->where('deleted_at', null);
    		$this->dbSource->where('display', 1);
    		$this->dbSource->orderBy($order_by, $sort);
    		$query = $this->dbSource->get();
    		if ($query->resultID->num_rows > 0) {
    			$result = $query->getResultArray();
    			return $result;
    		} else {
    			return null;
    		}
    	}
    
    	/* 按條件獲取表內數據(不包含deleted_at已刪除數據)
    	 * 允許指定 select內容
    	 * 返回數組
    	 *  @return multiple array
    	 */
    
    	public function db_all_data_by_select($table_name = '', $select = array('id'), $where = array(), $where_in = array(), $or_like = array(), $timeRange = array(), $order_by = 'sort', $sort = 'desc', $include_delete = false, $or_where = array(), $include_display = false, $group_by = null) {
    		$order_by = $order_by === null ? 'created_at' : $order_by;
    		$sort = $sort === null ? 'DESC' : $sort;
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		/* 獲取數據 */
    		$this->dbSource->select($select);
    		if (!empty($or_where)) {
    			$this->dbSource->groupStart();
    			foreach ($or_where as $o_key => $o_value) {
    				if (is_array($o_value) && count($o_value) == 3 && isset($o_value['field']) && isset($o_value['value']) && isset($o_value['escape'])) {
    					$this->dbSource->orWhere($o_value['field'], $o_value['value'], $o_value['escape']);
    				}
    			}
    			$this->dbSource->groupEnd();
    		}
    		if (!empty($or_like)) {
    			$this->dbSource->groupStart();
    			$this->dbSource->orLike($or_like);
    			$this->dbSource->groupEnd();
    		}
    
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    
    		if (!empty($timeRange)) {
    			if (isset($timeRange['timeRangeStyle'])) {
    				$timeRangeStyle = intval($timeRange['timeRangeStyle']);
    				if ($timeRangeStyle === 1) {
    					if (isset($timeRange['start']) && $timeRange['start']) {
    						$this->dbSource->where('created_at >=', $timeRange['start']);
    					}
    					if (isset($timeRange['end']) && $timeRange['end']) {
    						$this->dbSource->where('created_at <=', $timeRange['end']);
    					}
    				} else if ($timeRangeStyle === 2) {
    					$this->dbSource->where('created_at IS NULL');
    				}
    			}
    		}
    		if (!$include_delete) {
    			$this->dbSource->where('deleted_at', null);
    		}
    		if (!$include_display) {
    			$this->dbSource->where('display', 1);
    		}
    		if ($order_by !== FALSE) {
    			$this->dbSource->orderBy($order_by, $sort);
    		}
    		$query = $this->dbSource->get();
    		if ($query->resultID->num_rows > 0) {
    			$result = $query->getResultArray();
    			return $result;
    		} else {
    			return null;
    		}
    	}
    
    	/* 按分頁獲取數據
    	 *  @return multiple array
    	 */
    
    	public function db_page_data($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $order_by, $sort, $page, $num, $countOnly = false, $dataType = 'active', $dataTypes = ['active', 'delete'], $returnSql = false, $select = '*') {
    		$order_by = $order_by === null ? 'created_at' : $order_by;
    		$sort = $sort === null ? 'DESC' : $sort;
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		/* 獲取數量 */
    		$this->dbSource = $this->db->table($table_name);
    
    		$counts = [];
    		
    		if ($dataTypes) {
    			foreach ($dataTypes as $type) {
    				/* 獲取正常數量 */
    				$this->dbSource->select('count(*) AS num');
    				$this->pagedata_set($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $type);
    				$query = $this->dbSource->get();
    				if ($query->resultID->num_rows > 0) {
    					$count_result = $query->getRowArray();
    					$number = $count_result['num'];
    				} else {
    					$number = null;
    				}
    				$counts[$type] = $number;
    			}
    		}
    		if (empty($dataType)) {
    			$dataType = 'active';
    		}
    		if (array_key_exists($dataType, $counts)) {
    			$count = $counts[$dataType];
    			if ($count === null) {
    				return null;
    			} else {
    				if ($countOnly === true) {
    					return $count;
    				}
    			}
    		} else {
    			return false;
    		}
    		/* 獲取分頁數據 */
    		$this->dbSource->select($select);
    //		dump($select);
    //		die();
    		$this->pagedata_set($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType);
    		$this->dbSource->orderBy($order_by, $sort);
    		if ($page != null && $num != null) {
    			if ($num !== '全部' && $num !== 'all') {
    				$offset = ($page - 1) * $num;
    				$this->dbSource->limit($num, $offset);
    			}
    		}
    		$query = $this->dbSource->get();
    		if ($returnSql) {
    			$getLastQuery = $this->db->getLastQuery();
    			$returnSqlStr = $getLastQuery->getQuery();
    		} else {
    			$returnSqlStr = '';
    		}
    		/* 註釋 */
    		if ($this->db->fieldExists('sort', $table_name)) {
    			if ($page != null && $num != null) {
    				if ($num !== '全部' && $num !== 'all') {
    					$sortData = $this->getSortData($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType, $order_by, $sort, $offset, $num, $count);
    				}
    			} else {
    				$sortData = array();
    			}
    		} else {
    			$sortData = array();
    		}
    		if ($query->resultID->num_rows > 0) {
    			$result = $query->getResultArray();
    			$return = array();
    			$return['count'] = $count;
    			$return['counts'] = $counts;
    			$return['data'] = $result;
    			$return['sort'] = $sortData;
    			if ($returnSql) {
    				$return['returnSqlStr'] = $returnSqlStr;
    			}
    			return $return;
    		} else {
    			return null;
    		}
    	}
    
    	/* db_page_data 查詢條件的集合 */
    
    	public function pagedata_set($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType) {
    		if (!empty($where)) {
    			$this->dbSource->groupStart();
    			if (!empty($where)) {
    				foreach ($where as $w_key => $w_value) {
    					if ($w_value === 'null') {
    						$this->dbSource->where($w_key, null);
    					} elseif ($w_value === '!=null') {
    						$this->dbSource->where($w_key . ' !=', null);
    					} else {
    						$this->dbSource->where($w_key, $w_value);
    					}
    				}
    			}
    			$this->dbSource->groupEnd();
    		}
    		if (!empty($or_where)) {
    			$this->dbSource->groupStart();
    			foreach ($or_where as $o_key => $o_value) {
    				if (is_array($o_value) && count($o_value) == 3 && isset($o_value['field']) && isset($o_value['value']) && isset($o_value['escape'])) {
    					$this->dbSource->orWhere($o_value['field'], $o_value['value'], $o_value['escape']);
    				}
    			}
    			$this->dbSource->groupEnd();
    		}
    		if (!empty($or_like)) {
    			$this->dbSource->groupStart();
    			foreach ($or_like as $l_key => $like) {
    				if (is_string($like)) {
    					$this->dbSource->orLike($l_key, $like);
    				} elseif (is_array($like) && count($like) == 4 && isset($like['field']) && isset($like['match']) && isset($like['side']) && isset($like['escape'])) {
    					$this->dbSource->orLike($like['field'], $like['match'], $like['side'], $like['escape']);
    				}
    			}
    			$this->dbSource->groupEnd();
    		}
    
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value) || $w_value === 0) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    		if (!empty($timeRange)) {
    			if (isset($timeRange['timeRangeStyle'])) {
    				$timeRangeStyle = intval($timeRange['timeRangeStyle']);
    				if ($timeRangeStyle !== 2) {
    					if (isset($timeRange['start']) && $timeRange['start']) {
    						$this->dbSource->where('created_at >=', $timeRange['start']);
    					}
    					if (isset($timeRange['end']) && $timeRange['end']) {
    						$this->dbSource->where('created_at <=', $timeRange['end']);
    					}
    				} else if ($timeRangeStyle === 2) {
    					$this->dbSource->where('created_at IS NULL');
    				}
    			} else {
    				if (isset($timeRange['start']) && $timeRange['start']) {
    					$this->dbSource->where('created_at >=', $timeRange['start']);
    				}
    				if (isset($timeRange['end']) && $timeRange['end']) {
    					$this->dbSource->where('created_at <=', $timeRange['end']);
    				}
    			}
    		}
    		switch ($dataType) {
    			case 'active':
    				$this->dbSource->where('deleted_at', null);
    				break;
    			case 'delete':
    				$this->dbSource->where('deleted_at !=', null);
    				break;
    			case 'all':
    				break;
    			default:
    				$this->dbSource->where('deleted_at', null);
    				break;
    		}
    		$this->dbSource->where('display', 1);
    	}
    
    	/* 獲取當前頁數據的
    	 * 上一頁最後一條數據id
    	 * 下一頁第一條數據id
    	 * 搜索結果(所有分頁中)最大排序的id (用於置頂操作)
    	 *  */
    
    	public function getSortData($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType, $order_by, $sort, $offset, $num, $count) {
    		$this->dbSource->select('*');
    		$this->pagedata_set($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType);
    		$this->dbSource->orderBy('sort', 'DESC');
    		$this->dbSource->limit(1, 0);
    		$topSortRow = $this->dbSource->get();
    		$topSortRowData = $topSortRow->resultID->num_rows > 0 ? $topSortRow->getRowArray() : null;
    		if ($offset - 1 >= 0) {
    			$this->dbSource->select('*');
    			$this->pagedata_set($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType);
    			$this->dbSource->orderBy($order_by, $sort);
    			$this->dbSource->limit(1, $offset - 1);
    			$prevPageLastRow = $this->dbSource->get();
    			$prevPageLastRowData = $prevPageLastRow->resultID->num_rows > 0 ? $prevPageLastRow->getRowArray() : null;
    		}
    		if ($offset + $num <= ($count - 1)) {
    			$this->dbSource->select('*');
    			$this->pagedata_set($table_name, $where, $or_where, $where_in, $or_like, $timeRange, $dataType);
    			$this->dbSource->orderBy($order_by, $sort);
    			$this->dbSource->limit(1, $offset + $num);
    			$nextPageFirstRow = $this->dbSource->get();
    			$nextPageFirstRowData = $nextPageFirstRow->resultID->num_rows > 0 ? $nextPageFirstRow->getRowArray() : null;
    		}
    		$topId = $topSortRowData ? $topSortRowData['id'] : null;
    		$prevPageLastId = isset($prevPageLastRowData) && $prevPageLastRowData ? $prevPageLastRowData['id'] : null;
    		$newxPageFirstId = isset($nextPageFirstRowData) && $nextPageFirstRowData ? $nextPageFirstRowData['id'] : null;
    		return array("topId" => $topId, "prevPageLastId" => $prevPageLastId, "newxPageFirstId" => $newxPageFirstId);
    	}
    
    	public function db_insert_row($table_name = '', $params, $changeLog = true, $idColumn = null) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		$this->dbSource->insert($params);
    		
    	
    		$insert_id = $this->db->insertID();
    		$changeLog ? $this->insertChangeLog(array($tbid = $this->db->insertID()), $table_name, $idColumn) : ''; //在insert之後保存插入的日誌記錄
    		if ($this->db->affectedRows()) {
    			if ($this->db->fieldExists('sort', $table_name)) {
    				if($table_name !== 'log'){
    					$maxSortSql = "UPDATE `" . $table_name . "` SET sort = (SELECT MS.msort FROM (select(max(sort)) AS msort from `$table_name`) AS MS)+1 WHERE `id` = $insert_id";
    				}else{
    					$maxSortSql = "UPDATE `" . $table_name . "` SET sort = $insert_id";
    				}
    				$this->db->query($maxSortSql);
    			}
    			return $insert_id;
    		} else {
    			return false;
    		}
    	}
    
    	/* 批量插入數據庫
    	 * 如果有sort(排序號)字段會自動添加排序號
    	 */
    
    	public function db_insertBatch($table_name = '', $params, $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($this->db->fieldExists('sort', $table_name)) {
    			$maxSortSql = "SELECT max(sort) AS maxsort FROM " . $table_name;
    			$maxSort = $this->db->query($maxSortSql);
    			if ($maxSort && $maxSort->getRowArray()) {
    				$maxSortQuery = $maxSort->getRowArray();
    				$maxSortNum = $maxSortQuery['maxsort'];
    				foreach ($params as $key => $value) {
    					$params[$key]['sort'] = $maxSortNum + 1;
    					$maxSortNum ++;
    				}
    			} else {
    				return false;
    			}
    		}
    		$this->dbSource->insertBatch($params);
    		if ($this->db->affectedRows()) {
    			$insert_id = $this->db->insertID();
    			if ($changeLog && $this->db->fieldExists('sort', $table_name)) {//記錄日誌
    				$sorts = array_column($params, 'sort');
    				$idList = $this->dbSource->select('group_concat(id) AS ids')->whereIn('sort', $sorts)->get()->getRowArray();
    				if (!empty($idList['ids'])) {
    					$this->insertChangeLog(explode(',', $idList['ids'])); //在insert之後保存插入的日誌記錄
    				}
    			}
    			return $insert_id;
    		} else {
    			return false;
    		}
    	}
    
    	/* 批量更新數據
    	 * 如果有updated_at字段會自動更新該字段
    	 */
    
    	public function db_update_batch($params, $primary_key, $table_name, $where = array(), $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		if (empty($primary_key)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		$indexArr = array_column($params, $primary_key);
    		if ($changeLog) {
    			$this->dbSource->select('group_concat(id) AS ids');
    			$this->dbSource->whereIn($primary_key, $indexArr);
    			if (!empty($where)) {
    				$this->dbSource->where($where);
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->updateStartBatch(explode(',', $idStr['ids']), $table_name, $type = 2); //日誌開始標識
    				$updateStartBatch = true;
    			}
    		}
    		$this->dbSource->updateBatch($params, $primary_key);
    		$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    		if ($this->db->affectedRows()) {
    			if ($this->db->fieldExists('updated_at', $table_name)) {
    				$this->dbSource->whereIn($primary_key, $indexArr);
    				$this->dbSource->set('updated_at', 'now()', false);
    				$this->dbSource->update();
    			}
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	public function db_update_row($table_name = '', $update = array(), $id = null, $escape = true, $updated_at = true, $where = array(), $changeLog = true, $returnSql = false) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($changeLog) {
    			$this->dbSource->select('group_concat(id) AS ids');
    			if (!empty($id)) {
    				if (!empty($id)) {//不能省略
    					$this->dbSource->where('id', $id);
    				} else {
    					return false;
    				}
    			} else {
    				if ($id === false || $id === null) {
    					$whereNotEmpty = false;
    					if (!empty($where)) {
    						foreach ($where as $key => $value) {
    							if (!empty($value)) {
    								$whereNotEmpty = true;
    							}
    						}
    					}
    					if ($whereNotEmpty !== true) {
    						$this->show_msg(3001, '請設置id和where');
    					} else {
    						$this->dbSource->where($where);
    					}
    				} else {
    					$this->show_msg(3001, '請設置id');
    				}
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->updateStartBatch(explode(',', $idStr['ids']), $table_name, $type = 2); //日誌開始標識
    				$updateStartBatch = true;
    			}
    		}
    		if (!empty($id)) {
    			$this->dbSource->where('id', $id);
    		} else {
    			if ($id === false || $id === null) {
    				$whereNotEmpty = false;
    				if (!empty($where)) {
    					foreach ($where as $key => $value) {
    						if (!empty($value)) {
    							$whereNotEmpty = true;
    						}
    					}
    				}
    				if ($whereNotEmpty !== true) {
    					$this->show_msg(3001, '請設置id和where');
    				}
    			} else {
    				$this->show_msg(3001, '請設置id');
    			}
    		}
    		if ($escape === true) {
    			foreach ($update as $key => $value) {
    				$this->dbSource->set($key, $value);
    			}
    		} elseif ($escape === false && !empty($update)) {
    			foreach ($update as $key => $value) {
    				if ($value === null) {
    					$this->dbSource->set($key, $value);
    				} else {
    					$this->dbSource->set($key, $value, false);
    				}
    			}
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		$this->dbSource->update();
    		if (!$returnSql) {
    			//中間放更新操作代碼
    			$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    			if ($this->db->affectedRows()) {
    				if ((!empty($id) || !empty($where)) && $this->db->fieldExists('updated_at', $table_name) && $updated_at === true) {
    					$this->dbSource->set('updated_at', 'now()', false);
    					if (!empty($id)) {
    						$this->dbSource->where('id', $id);
    					}
    					if (!empty($where)) {
    						$this->dbSource->where($where);
    					}
    					$this->dbSource->update();
    				}
    				return true;
    			} else {
    				return false;
    			}
    		} else {
    			$getLastQuery = $this->db->getLastQuery();
    			return $getLastQuery->getQuery();
    		}
    	}
    
    	public function db_destory_row($table_name = '', $id = null, $where = array(), $changeLog = true, $returnSql = false) {
    		
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($changeLog) {
    			$this->dbSource->select('group_concat(id) AS ids');
    			if (!empty($id)) {
    				if (!empty($id)) {//不能省略
    					$this->dbSource->where('id', $id);
    				} else {
    					return false;
    				}
    			} else {
    				if ($id === false || $id === null) {
    					$whereNotEmpty = false;
    					if (!empty($where)) {
    						foreach ($where as $key => $value) {
    							if (!empty($value)) {
    								$whereNotEmpty = true;
    							}
    						}
    					}
    					if ($whereNotEmpty !== true) {
    						$this->show_msg(3001, '請設置id和where');
    					} else {
    						$this->dbSource->where($where);
    					}
    				} else {
    					$this->show_msg(3001, '請設置id');
    				}
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->updateStartBatch(explode(',', $idStr['ids']), $tbname = '', $type = 2); //日誌開始標識
    				$updateStartBatch = true;
    			}
    		}
    		if (!empty($id)) {
    			$this->dbSource->where('id', $id);
    		} else {
    			if ($id === false || $id === null) {
    				$whereNotEmpty = false;
    				if (!empty($where)) {
    					foreach ($where as $key => $value) {
    						if (!empty($value)) {
    							$whereNotEmpty = true;
    						}
    					}
    				}
    				if ($whereNotEmpty !== true) {
    					$this->show_msg(3001, '請設置id和where');
    				}
    			} else {
    				$this->show_msg(3001, '請設置id');
    			}
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		$this->dbSource->delete();
    //		echo '<br/>';
    //		var_dump(__FILE__);
    //		echo '<br/>';
    //		var_dump(__LINE__);
    //		die();
    		if (!$returnSql) {
    			//中間放更新操作代碼
    			$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    			if ($this->db->affectedRows()) {
    				return true;
    			} else {
    				return false;
    			}
    		} else {
    			$getLastQuery = $this->db->getLastQuery();
    			return $getLastQuery->getQuery();
    		}
    	}
    	public function db_alter_row($table_name, $columnName, $dataType, $length, $ifNull, $default, $comments, $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		if ($this->db->fieldExists($columnName, $table_name)) {
    			dump(array($table_name, $columnName, $dataType, $length, $ifNull, $default, $comments));
    			die();
    		}
    		$sql = "ALTER TABLE `$table_name` ADD `$columnName` $dataType($length) $ifNull DEFAULT ";
    		if ($default === '') {
    			$sql .= "'" . $default . "'";
    		} else {
    			$sql .= $default;
    		}
    		if (!empty($comments)) {
    			$sql .= " COMMENT '$comments' ";
    		}
    		$this->db->query($sql);
    //		$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    		if ($this->db->affectedRows()) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	public function db_field_exist($fieldName, $table_name) {
    		$this->dbSource = $this->db->table($table_name);
    		if ($this->db->fieldExists($fieldName, $table_name)) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	/* 更新數據
    	 * 如果有updated_at字段會自動更新該字段
    	 */
    
    	public function db_update_where($table_name = '', $update = array(), $where = array(), $escape = true, $updated_at = true, $where_in = null, $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($changeLog) {
    			$this->dbSource->select('group_concat(id) AS ids');
    			if (!empty($where)) {
    				$this->dbSource->where($where);
    			}
    			if (!empty($where_in)) {
    				foreach ($where_in as $field => $where_in_params) {
    					$whereInFliter = array();
    					if (!empty($where_in_params)) {
    						foreach ($where_in_params as $w_value) {
    							if (!empty($w_value)) {
    								$whereInFliter[] = $w_value;
    							}
    						}
    					}
    					if (!empty($whereInFliter)) {
    						$this->dbSource->whereIn($field, $whereInFliter);
    					}
    				}
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->updateStartBatch(explode(',', $idStr['ids']), $table_name, $type = 2); //日誌開始標識
    				$updateStartBatch = true;
    			}
    		}
    		if ($escape === true) {
    			$this->dbSource->set($update);
    		} elseif ($escape === false && !empty($update)) {
    			foreach ($update as $key => $value) {
    				if ($value === null) {
    					$this->dbSource->set($key, $value);
    				} else {
    					$this->dbSource->set($key, $value, false);
    				}
    			}
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    					if (!empty($whereInFliter)) {
    						$this->dbSource->whereIn($field, $whereInFliter);
    					} else {
    						return false;
    					}
    				}
    			}
    		}
    		$this->dbSource->update();
    		$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    		if ($this->db->affectedRows()) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	/* 將單條數據設置爲刪除狀態
    	 */
    
    	public function db_delete_row($id = null, $table_name = '', $where = array(), $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    
    		$this->dbSource = $this->db->table($table_name);
    		if ($changeLog) {//日誌處理
    			$this->dbSource->select('group_concat(id) AS ids');
    			if (!empty($where)) {
    				$this->dbSource->where($where);
    			}
    			if (!empty($id)) {
    				$this->dbSource->where('id', $id);
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->deleteChangeLog(explode(',', $idStr['ids'])); //日誌開始標識
    			}
    		}
    		if (!empty($id)) {
    			$id = intval($id);
    			if (!empty($id)) {//不能省略
    				$this->dbSource->where('id=' . intval($id));
    			} else {
    				return false;
    			}
    		} else {
    			if ($id === false || $id === null) {
    				$whereNotEmpty = false;
    				if (!empty($where)) {
    					foreach ($where as $key => $value) {
    						if (!empty($value)) {
    							$whereNotEmpty = true;
    						}
    					}
    				}
    				if ($whereNotEmpty !== true) {
    					$this->show_msg(3001, '請設置id和where');
    				}
    			} else {
    				$this->show_msg(3001, '請設置id');
    			}
    		}
    		$this->dbSource->set('updated_at', 'now()', false);
    		$this->dbSource->set('deleted_at', 'now()', false);
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		$this->dbSource->update();
    		if ($this->db->affectedRows()) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	/* 批量設置爲刪除狀態
    	 */
    
    	public function db_delete_batch($idList = array(), $table_name = '', $where = array(), $where_in = array(), $changeLog = true, $returnSql = false) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($changeLog) {//日誌處理
    			$this->dbSource->select('group_concat(id) AS ids');
    			if (!empty($where)) {
    				$this->dbSource->where($where);
    			}
    			if (!empty($idList)) {
    				$this->dbSource->whereIn('id', $idList);
    			} else {
    				$whereNotEmpty = false;
    				if (!empty($where)) {
    					foreach ($where as $key => $value) {
    						if (!empty($value)) {
    							$whereNotEmpty = true;
    						}
    					}
    				}
    				if (empty($where) && $whereNotEmpty === false && empty($where_in)) {
    					$this->show_msg(3001, '請設置刪除條件');
    				} else {
    					$this->dbSource->where($where);
    				}
    			}
    			if (!empty($where_in)) {
    				foreach ($where_in as $field => $where_in_params) {
    					$whereInFliter = array();
    					if (!empty($where_in_params)) {
    						foreach ($where_in_params as $w_value) {
    							if (!empty($w_value)) {
    								$whereInFliter[] = $w_value;
    							}
    						}
    					}
    					if (!empty($whereInFliter)) {
    						$this->dbSource->whereIn($field, $whereInFliter);
    					}
    				}
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->updateStartBatch(explode(',', $idStr['ids']), $table_name, $type = 3); //日誌開始標識
    				$updateStartBatch = true;
    			}
    		}
    		if (!empty($idList)) {
    			$this->dbSource->whereIn('id', $idList);
    		} else {
    			$whereNotEmpty = false;
    			if (!empty($where)) {
    				foreach ($where as $key => $value) {
    					if (!empty($value)) {
    						$whereNotEmpty = true;
    					}
    				}
    			}
    			if (empty($where) && $whereNotEmpty === false && empty($where_in)) {
    				$this->show_msg(3001, '請設置刪除條件');
    			}
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    		$this->dbSource->set('updated_at', 'now()', false);
    		$this->dbSource->set('deleted_at', 'now()', false);
    		$this->dbSource->update();
    		if (!$returnSql) {
    			$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    			if ($this->db->affectedRows()) {
    				return true;
    			} else {
    				return false;
    			}
    		} else {
    			$this->db = \Config\Database::connect();
    			$getLastQuery = $this->db->getLastQuery();
    			return $getLastQuery->getQuery();
    		}
    	}
    
    	/* 批量設置爲不可見
    	 */
    
    	public function db_undisplay_batch($idList = array(), $table_name = '', $where = array(), $where_in = array(), $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($changeLog) {
    			$this->dbSource->select('group_concat(id) AS ids');
    			if (!empty($idList)) {
    				$this->dbSource->whereIn('id', $idList);
    			} else {
    				$whereNotEmpty = false;
    				if (!empty($where)) {
    					foreach ($where as $key => $value) {
    						if (!empty($value)) {
    							$whereNotEmpty = true;
    						}
    					}
    				}
    				if (empty($where) && $whereNotEmpty === false && empty($where_in)) {
    					$this->show_msg(3001, '請設置刪除條件');
    				}
    			}
    			if (!empty($where)) {
    				$this->dbSource->where($where);
    			}
    			if (!empty($where_in)) {
    				foreach ($where_in as $field => $where_in_params) {
    					$whereInFliter = array();
    					if (!empty($where_in_params)) {
    						foreach ($where_in_params as $w_value) {
    							if (!empty($w_value)) {
    								$whereInFliter[] = $w_value;
    							}
    						}
    					}
    					if (!empty($whereInFliter)) {
    						$this->dbSource->whereIn($field, $whereInFliter);
    					}
    				}
    			}
    			/* 即將更新的id */
    			$idStr = $this->dbSource->get()->getRowArray();
    			if (!empty($idStr) && !empty($idStr['ids'])) {
    				$this->updateStartBatch(explode(',', $idStr['ids']), $table_name, $type = 4); //日誌開始標識
    				$updateStartBatch = true;
    			}
    		}
    		if (!empty($idList)) {
    			$this->dbSource->whereIn('id', $idList);
    		} else {
    			$whereNotEmpty = false;
    			if (!empty($where)) {
    				foreach ($where as $key => $value) {
    					if (!empty($value)) {
    						$whereNotEmpty = true;
    					}
    				}
    			}
    			if (empty($where) && $whereNotEmpty === false && empty($where_in)) {
    				$this->show_msg(3001, '請設置刪除條件');
    			}
    		}
    		if (!empty($where)) {
    			$this->dbSource->where($where);
    		}
    		if (!empty($where_in)) {
    			foreach ($where_in as $field => $where_in_params) {
    				$whereInFliter = array();
    				if (!empty($where_in_params)) {
    					foreach ($where_in_params as $w_value) {
    						if (!empty($w_value)) {
    							$whereInFliter[] = $w_value;
    						}
    					}
    				}
    				if (!empty($whereInFliter)) {
    					$this->dbSource->whereIn($field, $whereInFliter);
    				}
    			}
    		}
    		$this->dbSource->set('display', 0);
    		$this->dbSource->set('updated_at', 'now()', false);
    		$this->dbSource->set('deleted_at', 'now()', false);
    		$this->dbSource->update();
    		$changeLog && isset($updateStartBatch) && $updateStartBatch ? $this->updateEndBatch() : ''; //日誌結束標識
    		if ($this->db->affectedRows()) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	/* 批量恢復爲未刪除狀態
    	 */
    
    	public function db_recover_batch($idList = array(), $table_name = '', $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$changeLog ? $this->updateStartBatch($idList, $tbname = '', $type = 5) : ''; //日誌開始標識
    		$this->dbSource = $this->db->table($table_name);
    		if (!empty($idList)) {
    			$this->dbSource->whereIn('id', $idList);
    		} else {
    			$this->show_msg(3001, '請設置id');
    		}
    		$this->dbSource->set('updated_at', 'now()', false);
    		$this->dbSource->set('deleted_at', 'null', false);
    		$this->dbSource->update();
    		$changeLog ? $this->updateEndBatch() : ''; //日誌結束標識
    		if ($this->db->affectedRows()) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	/* 交換兩條記錄的排序值 */
    
    	public function db_exchange_sort($first_id = null, $second_id = null, $table_name = '', $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($first_id === null || $second_id === null) {
    			return false;
    		}
    		$first_id = intval($first_id);
    		$second_id = intval($second_id);
    		$id_arr = array($first_id, $second_id);
    		$changeData = $this->db_array($table_name, $page = null, $num = null, $where = array(), $where_in = array('id' => $id_arr), $like = array());
    		if ($changeData && count($changeData) === 2) {
    			$first_sort = $changeData[0]['sort'];
    			$second_sort = $changeData[1]['sort'];
    			$query = "update `" . $table_name . "` set sort=if(sort=$first_sort,$second_sort,$first_sort) where sort in ($first_sort,$second_sort)";
    			$changeLog ? $this->updateStartBatch($idList = $id_arr, $table_name, $type = 6) : ''; //日誌開始標識
    			$this->db->query($query);
    			$changeLog ? $this->updateEndBatch() : ''; //日誌結束標識
    			if ($this->db->affectedRows()) {
    				return true;
    			} else {
    				return false;
    			}
    		} else {
    			return false;
    		}
    	}
    
    	/* 將選中記錄的排序值從搜索結果置頂爲最大 */
    
    	public function db_sort_to_top($select_id = null, $top_id = null, $table_name = '', $changeLog = true) {
    		$table_name = $table_name ? $table_name : $this->default_table_name($table_name);
    		if (empty($table_name)) {
    			return false;
    		}
    		$this->dbSource = $this->db->table($table_name);
    		if ($select_id === null || $top_id === null) {
    			return false;
    		}
    		$select_id = intval($select_id);
    		$top_id = intval($top_id);
    		$select_data = $this->db_row($table_name, $id = null, $where = array('id' => $select_id));
    		$top_data = $this->db_row($table_name, $id = null, $where = array('id' => $top_id));
    		if ($select_data && $top_data) {
    			$select_sort = $select_data['sort'];
    			$top_sort = $top_data['sort'];
    			if ($select_sort >= $top_sort) {
    				return false;
    			}
    			$query = "update `" . $table_name . "` set sort=if(sort>$top_sort,sort+1,if(sort=$select_sort,$top_sort+1,sort)) where sort = $select_sort OR  sort >= $top_sort";
    			$changeLog ? $this->updateStartBatch($idList = array($select_id, $top_id), $table_name, $type = 6) : ''; //日誌開始標識
    			$this->db->query($query);
    			$changeLog ? $this->updateEndBatch() : ''; //日誌結束標識
    			if ($this->db->affectedRows()) {
    				return true;
    			} else {
    				return false;
    			}
    		} else {
    			return false;
    		}
    	}
    
    	/* 日誌記錄處理
    	 * $tbidList  監視數據變化的id數組
    	 * $tbname 數據表
    	 * $type 操作類型  1:插入數據 2:修改 3:標記刪除 4:徹底刪除 5:恢復數據 6:更改排序 
    	 */
    
    	public function updateStartBatch($tbidList, $tbname = '', $type = 2) {
    		$tbname = $tbname ? $tbname : $this->default_table_name($tbname);
    		if (empty($tbname)) {
    			return false;
    		}
    		$db = \Config\Database::connect();
    		//查詢表註釋
    		$query = $db->query('show table status where name = "' . $tbname . '"');
    		$tb = $query->getRowArray();
    		//查詢修改前數據信息
    		$rsList = $db->query("SELECT * FROM `$tbname` WHERE `id` IN ('" . implode("','", $tbidList) . "') ")->getResultArray();
    		$keyValueList = [];
    		if (!empty($rsList)) {
    			foreach ($rsList as $rs) {
    				$keyValue = [];
    				$keyValue['keys'] = array_keys($rs);
    				$keyValue['values'] = array_values($rs);
    				$keyValueList[$rs['id']] = $keyValue;
    			}
    		}
    		$this->tb = $tb;
    		$this->type = $type;
    		$this->tbidList = $tbidList;
    		$this->tbname = $tbname;
    		$this->keyValueList = $keyValueList;
    	}
    
    	/* 更新日誌結束 */
    
    	public function updateEndBatch() {
    		$db = \Config\Database::connect();
    		//查詢字段註釋
    		$field = $db->query('show full columns from `' . $this->tbname . '`')->getResultArray();
    		$commentArray = array();
    		foreach ($field as $v) {
    			$commentArray[$v['Field']] = $v['Comment'];
    		}
    		//查詢修改後數據信息
    		$rsList = $db->query("SELECT * FROM `$this->tbname` WHERE `id` IN ('" . implode("','", $this->tbidList) . "')")->getResultArray();
    //		dump( $this->keyValueList);
    //		dump($rsList);
    //		die();
    		if (!empty($rsList)) {
    			foreach ($rsList as $rs) {
    				$currentvalues = array_values($rs);
    				//前後信息進行比較
    				for ($i = 0; $i < count($currentvalues); $i++) {
    					$prevKeyValue = $this->keyValueList[$rs['id']];
    					if ($prevKeyValue['values'][$i] !== $currentvalues[$i]) {
    						$tb_log_content = $this->db->table('tb_log_content');
    						$tb_log_content->insert(array(
    							'tbkey' => $prevKeyValue['keys'][$i],
    							'tbvalue' => $prevKeyValue['values'][$i],
    							'currenttbvalue' => $currentvalues[$i],
    							'comment' => $commentArray[$prevKeyValue['keys'][$i]],
    							'tablename' => $this->tbname,
    							'reques_time_float' => $_SERVER['REQUEST_TIME_FLOAT'],
    							'http_cookie' => isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : '',
    							'type' => $this->type,
    							'tableid' => $rs['id'],
    							'tablename' => $this->tbname,
    							'tb_comment' => $this->tb['Comment'],
    							'dt' => date('Y-m-d H:i:s')
    						));
    					}
    				}
    			}
    		}
    	}
    
    	//刪除日誌
    	public function deleteChangeLog($tbidList, $tbname = '') {
    		$tbname = $tbname ? $tbname : $this->default_table_name($tbname);
    		if (empty($tbname)) {
    			return false;
    		}
    		$db = \Config\Database::connect();
    		//查詢表註釋
    		$tb = $db->query('show table status where name = "' . $tbname . '"')->getRowArray();
    		//插入日誌主表
    		//查詢字段註釋
    		$field = $db->query('show full columns from `' . $tbname . '`')->getResultArray();
    		foreach ($field as $v) {
    			$commentArray[$v['Field']] = $v['Comment'];
    		}
    		//查詢所有字段信息,插入日誌從表
    		$rsList = $db->query("SELECT * FROM `$tbname` WHERE `id` IN ('" . implode("','", $tbidList) . "')")->getResultArray();
    		$keyValueList = [];
    		if (!empty($rsList)) {
    			foreach ($rsList as $rs) {
    				$keyValue = [];
    				$keyValue['keys'] = array_keys($rs);
    				$keyValue['values'] = array_values($rs);
    				$keyValueList[$rs['id']] = $keyValue;
    			}
    		}
    		$insertLogs = [];
    		foreach ($rsList as $rs) {
    			$keys = $keyValueList[$rs['id']]['keys'];
    			$values = $keyValueList[$rs['id']]['values'];
    			for ($i = 0; $i < count($keys); $i++) {
    				$insertLogs[] = array(
    					'tbkey' => $keys[$i],
    					'tbvalue' => $values[$i],
    					'comment' => $commentArray[$keys[$i]],
    					'reques_time_float' => $_SERVER['REQUEST_TIME_FLOAT'],
    					'http_cookie' => isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : '',
    					'type' => '3',
    					'tableid' => $rs['id'],
    					'tablename' => $tbname,
    					'tb_comment' => $tb['Comment'],
    					'dt' => date('Y-m-d H:i:s')
    				);
    			}
    		}
    		$tb_log_content = $this->db->table('tb_log_content');
    		$tb_log_content->insertBatch($insertLogs);
    	}
    
    	/*	 * 添加數據日誌
    	 * 參數說明
    	 * int              $tbid       查詢指定表的id
    	 * string           $tbname     數據庫表名
    	 * string           $idColumn   記錄的自增字段名,默認爲id
    	 */
    
    	public function insertChangeLog($tbidList, $tbname = '', $idColumn = null) {
    		$tbname = $tbname ? $tbname : $this->default_table_name($tbname);
    		if (empty($tbname)) {
    			return false;
    		}
    		$db = \Config\Database::connect();
    		//查詢表註釋
    		$query = $db->query('show table status where name = "' . $tbname . '"');
    		$tb = $query->getRowArray();
    		//查詢字段註釋
    		$query = $db->query('show full columns from `' . $tbname . '`');
    		$field = $query->getResultArray();
    		foreach ($field as $v) {
    			$commentArray[$v['Field']] = $v['Comment'];
    		}
    		//查詢所有字段信息,插入日誌從表
    		if (empty($idColumn)) {
    			$idColumn = 'id';
    		}
    		$rsList = $db->query("SELECT * FROM `$tbname` WHERE `$idColumn` IN ('" . implode("','", $tbidList) . "')")->getResultArray();
    		$keyValueList = [];
    		if (!empty($rsList)) {
    			foreach ($rsList as $rs) {
    				$keyValue = [];
    				$keyValue['keys'] = array_keys($rs);
    				$keyValue['values'] = array_values($rs);
    				$keyValueList[$rs['id']] = $keyValue;
    			}
    		}
    		$insertLogs = [];
    		foreach ($rsList as $rs) {
    			$keys = $keyValueList[$rs['id']]['keys'];
    			$values = $keyValueList[$rs['id']]['values'];
    			for ($i = 0; $i < count($keys); $i++) {
    				$insertLogs[] = array(
    					'tbkey' => $keys[$i],
    					'tbvalue' => $values[$i],
    					'comment' => $commentArray[$keys[$i]],
    					'reques_time_float' => $_SERVER['REQUEST_TIME_FLOAT'],
    					'http_cookie' => isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : '',
    					'type' => '1',
    					'tableid' => $rs['id'],
    					'tablename' => $tbname,
    					'tb_comment' => $tb['Comment'],
    					'dt' => date('Y-m-d H:i:s')
    				);
    			}
    		}
    		$tb_log_content = $this->db->table('tb_log_content');
    		if (empty($insertLogs)) {
    			log_message('8', json_encode(array($tbidList, $tbname)));
    		}
    		$tb_log_content->insertBatch($insertLogs);
    	}
    
    
    	public function getTableColumnList($table_name) {
    		/* 選取數據表的註釋內容 */
    		$searchLicenseTableSql = "SELECT COLUMN_NAME,COLUMN_COMMENT FROM information_schema.COLUMNS WHERE table_name = '" . $table_name . "' AND TABLE_SCHEMA =  '" . $this->db->database . "'";
    
    		$query = $this->db->query($searchLicenseTableSql);
    		if ($query->resultID->num_rows >= 0) {
    			$result = $query->getResultArray();
    			return $result;
    		} else {
    			return null;
    		}
    	}
    
    	//$returnCrumbs 返回  局,所,區 形式的父子路徑
    	public function tree_parent_path_info($tableName, $searchId, $returnCrumbs = true, $implodeChar = ',', $nameField = 'name', $orderBy = 'root_level', $sortBy = 'asc') {
    		$tableName = trim($tableName);
    		if ($tableName && gettype($tableName) === 'string') {
    			$searchId = intval($searchId);
    			if ($searchId) {
    				$areaInfo = $this->db_row($table_name = $tableName, $id = $searchId, $where = array(), $order_by = null, $sort = 'desc', $include_delete = false, $select = '*', $include_display = false, $where_in = array());
    				if ($areaInfo) {
    					$pathArr = explode(',', $areaInfo['path']);
    					$pathFliterArr = [];
    					if (!empty($pathArr)) {
    						foreach ($pathArr as $d_key => $pathId) {
    							$pathId = intval($pathId);
    							if ($pathId) {
    								$pathFliterArr[] = $pathId;
    							}
    						}
    					}
    					if (!empty($pathFliterArr)) {
    						$where_in['id'] = $pathFliterArr;
    						$parents = $this->db_all_data_by_select($table_name = $tableName, $select = array('id', $nameField), $where = array(), $where_in, $or_like = array(), $timeRange = array(), $order_by = $orderBy, $sort = $sortBy, $include_delete = false, $or_where = array(), $include_display = false, $group_by = null);
    						if ($returnCrumbs) {
    							if ($parents) {
    								$nameArr = array_column($parents, $nameField);
    								$return = implode($implodeChar, $nameArr);
    							} else {
    								$return = '';
    							}
    						} else {
    							$return = $parents;
    						}
    					} else {
    						$return = false;
    					}
    				} else {
    					$return = null;
    				}
    			} else {
    				$return = false;
    			}
    		} else {
    			$return = false;
    		}
    		return $return;
    	}
    
    	/* 獲取數據樹形結構
    	 * $tableName = area
    	 * $pathField = area.path
    	 * $postIdValue = $this->trim_post('areaId')
    	 * $extraWhere = ""
    	 *  */
    
    	public function getDataTree($tableName, $pathField, $postIdValue = null, $extraWhere = "", $id_field = 'id', $parent_id_field = 'parent_id', $rootLevelField = 'root_level', $child_index = 'children', $orderBy = 'sort', $sortBy = 'desc') {
    		$whereArr = [];
    		if (!empty($postIdValue)) {
    			$whereArr[] = "FIND_IN_SET('$postIdValue',$pathField) != 0";
    		}
    		if (!empty($extraWhere)) {
    			$whereArr[] = $extraWhere;
    		}
    		$where = implode(' AND ', $whereArr);
    		$data = $this->db_all_data($table_name = $tableName, $where, $where_in = array(), $or_like = array(), $timeRange = array(), $order_by = $orderBy, $sort = $sortBy);
    		$level = 1;
    		$rootArray = $this->rootArray($data, array(), $level, $rootLevelField);
    		if (!empty($rootArray)) {
    			foreach ($rootArray as $b_key => $branch) {
    				$rootArray[$b_key][$child_index] = $this->branchChildren($data, $branch, $level, $id_field, $parent_id_field, $child_index);
    			}
    		}
    		return $rootArray;
    	}
    
    	protected function rootArray($data, $rootArray, &$level, $rootLevelField) {
    		if ($level > 6) {
    			return $rootArray;
    		} else {
    			if (empty($rootArray)) {
    				if (!empty($data)) {
    					foreach ($data as $value) {
    						if ($level === intval($value[$rootLevelField])) {
    							$rootArray[] = $value;
    						}
    					}
    				}
    			}
    			if (!empty($rootArray)) {
    				return $rootArray;
    			} else {
    				$level ++;
    				return $this->rootArray($data, $rootArray, $level, $rootLevelField);
    			}
    		}
    	}
    
    	protected function branchChildren($data, $branch, $level, $id_field, $parent_id_field, $child_index) {
    		$haveChildren = false;
    		if (!empty($data)) {
    			foreach ($data as $value) {
    				if (intval($value[$parent_id_field]) === intval($branch[$id_field])) {
    					$haveChildren = true;
    				}
    			}
    		}
    		if (!$haveChildren) {
    			return null;
    		} else {
    			$children = array();
    			foreach ($data as $value) {
    				if (intval($value[$parent_id_field]) === intval($branch[$id_field])) {
    					$value[$child_index] = $this->branchChildren($data, $value, $level, $id_field, $parent_id_field, $child_index);
    					$children[] = $value;
    				}
    			}
    			return $children;
    		}
    	}
    
    }
    
  12. 數據表標準
#sql數據表 標準字段數據表
CREATE TABLE `standred`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `sort` int(11) NOT NULL DEFAULT 0 COMMENT '排序',
  `note` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `display` tinyint(1) UNSIGNED NOT NULL DEFAULT 1 COMMENT '1:顯示  ',
  `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime(0) NULL DEFAULT NULL,
  `deleted_at` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '系統保留表:新建數據表時的標準' ROW_FORMAT = Dynamic;


#日誌表
CREATE TABLE `log`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `operate_content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `operator_name` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '操作人名稱/帳號名',
  `uri` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '訪問方法地址',
  `admin_id` int(11) NOT NULL DEFAULT 0,
  `user_id` int(11) NOT NULL DEFAULT 0,
  `shop_id` int(11) NOT NULL DEFAULT 0,
  `login_type` tinyint(1) NOT NULL COMMENT '1:web後臺 2:手機客戶端',
  `params` json NULL COMMENT '不規則參數保存 ',
  `ip` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT 'ip地址',
  `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime(0) NULL DEFAULT NULL,
  `deleted_at` datetime(0) NULL DEFAULT NULL,
  `display` tinyint(1) UNSIGNED NOT NULL DEFAULT 1 COMMENT '1:顯示  ',
  `reques_time_float` decimal(14, 4) UNSIGNED NOT NULL DEFAULT 0.0000 COMMENT '請求時間點,對應php服務器常量:$_SERVER[\'REQUEST_TIME_FLOAT\']',
  `http_cookie` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '對應php服務器常量:$_SERVER[\'HTTP_COOKIE\']',
  `privilege_id` int(10) UNSIGNED NULL DEFAULT NULL COMMENT '方法和權限關聯id',
  `sort` int(11) NOT NULL DEFAULT 0 COMMENT '排序',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `reques_time_float`(`reques_time_float`) USING BTREE,
  INDEX `http_cookie`(`http_cookie`) USING BTREE,
  INDEX `reques_time_float_2`(`reques_time_float`, `http_cookie`) USING BTREE,
  INDEX `privilege_id`(`privilege_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '日誌表' ROW_FORMAT = Dynamic;

#日誌內容表
CREATE TABLE `tb_log_content`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `tbkey` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
  `tbvalue` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
  `currenttbvalue` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
  `comment` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `reques_time_float` decimal(14, 4) UNSIGNED NOT NULL DEFAULT 0.0000 COMMENT '請求時間點,對應php服務器常量:$_SERVER[\'REQUEST_TIME_FLOAT\']',
  `http_cookie` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '對應php服務器常量:$_SERVER[\'HTTP_COOKIE\']',
  `type` int(1) NOT NULL DEFAULT 0 COMMENT '字段變動類型 1:插入數據 2:修改 3:標記刪除 4:徹底刪除 5:恢復數據 6:更改排序 ',
  `tableid` bigint(20) NULL DEFAULT NULL,
  `tablename` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '表名',
  `tb_comment` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `dt` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
  `display` tinyint(1) UNSIGNED NOT NULL DEFAULT 1 COMMENT '1:顯示  ',
  `created_at` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime(0) NULL DEFAULT NULL,
  `deleted_at` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`, `type`) USING BTREE,
  INDEX `reques_time_float`(`reques_time_float`) USING BTREE,
  INDEX `http_cookie`(`http_cookie`) USING BTREE,
  INDEX `reques_time_float_2`(`reques_time_float`, `http_cookie`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '系統日誌內容表' ROW_FORMAT = Dynamic;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章