| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 | <?phpnamespace daswork;use daswork\Config;use daswork\db\Mysql;class Model{	// 查询次数	public static $queryTimes = 0;	// 执行次数	public static $executeTimes = 0;	    // 数据库连接参数配置    protected $connection = [];	// 数据库查询对象池	protected static $links = [];	// 当前类名称	protected $class;	// 当前模型名称	protected $name;	// 当前查询对象    protected $query;    // 当前数据表名称(含前缀)    protected $tablename = '';    // 当前数据表名称(不含前缀)    protected $table = '';    // 当前数据表主键    protected $pk;    // 当前数据表前缀    protected $prefix = '';    // 查询参数    protected $options = [];    // 最近查询的 sql 语句    public $sql = '';	/**     * 初始化过的模型.     *     * @var array     */    protected static $initialized = [];	public function __construct()	{		// 当前类名		$this->class = get_called_class();		if (empty($this->name)) {			// 当前模型名			$name = str_replace('\\', '/', $this->class);			$this->name = basename($name);        }                // 合并数据库配置        if (!empty($this->connection) && is_array($this->connection)) {            $connection = array_merge(Config::get('db'), $this->connection);        } else {            $connection = Config::get('db');        }            $this->connection = $connection;        // 设置当前数据表和模型名        if (isset($connection['prefix'])) {            $this->prefix = $connection['prefix'];        }        if (!empty($this->table)) {            $this->tablename = $this->prefix .  $this->table;        } else {            $this->tablename = $this->prefix . uncamelize($this->name);        }		// 执行初始化操作		$this->initialize();    }        /**     *  初始化模型     * @access protected     * @return void     */    protected function initialize()    {        $class = get_class($this);        if (!isset(static::$initialized[$class])) {            static::$initialized[$class] = true;            static::init();        }	}		/**     * 初始化处理     * @access protected     * @return void     */    protected static function init()    {    }    /**     * 获取当前模型的查询对象     * @access public     * @param bool      $buildNewQuery  创建新的查询对象     * @return Query     */    public function getQuery($buildNewQuery = false)    {        if ($buildNewQuery) {            return Mysql::connect($this->connection);        } elseif (!isset(self::$links[$this->class])) {            // 创建模型查询对象            self::$links[$this->class] = Mysql::connect($this->connection);        }        return self::$links[$this->class];    }    /**     * 指定默认数据表名(含前缀)     * @access public     * @param string $table 表名     * @return $this     */    public function setTablename($tablename)    {        $this->tablename = $tablename;    }    /**     * 得到当前或者指定名称的数据表     * @access public     * @param string $name     * @return string     */    public function getTablename()    {        return $this->tablename;    }	/**     * 执行sql     * @param string $sql     * @return mixd $res     */    public function exec($sql)    {        @$res = $this->getQuery()->exec($sql);        $this->$sql = $sql;        return $res;    }    public function query($sql)    {        $result = $this->getQuery()->query($sql);        $this->$sql = $sql;        return $result;    }        public function lastInsertRowID ()    {        $result = $this->getQuery()->lastInsertRowID();        return $result;    }    public function lastErrorMsg()    {        return $this->getQuery()->lastErrorMsg();    }    /**     * 查询数组列表     */    public function select($sql)    {        $result = $this->getQuery()->query($sql);        $data = array();        while ($arr = $result->fetch_assoc()) {            $data[] = $arr;        }        return $data;    }    /**     * 列表结果集     */    public function list($where='')    {        $sql = "select * from $this->tablename $where;";        return $this->select($sql);    }    /**     * 查询一条     */    public function getOneById($id, $tablename='')    {        $tablename = $tablename ? $tablename : $this->tablename;        $sql = "SELECT * FROM `$tablename` WHERE `id`=$id;";        $result = $this->getQuery()->query($sql);        // var_dump($result);        $data = $result->fetch_all(MYSQLI_ASSOC);        // var_dump($data);        return $data;    }    /**     * 单列合计     */    public function sumColumn($column, $tablename)    {        $tablename = $tablename ? $tablename : $this->tablename;        $sql = "SELECT sum(`$column`) as sumData FROM `$tablename`;";        $result = $this->getQuery()->query($sql);        // $data = $result->fetch_assoc();        // var_dump($data['sumData']);exit;        if ($data = $result->fetch_assoc()) {            return $data['sumData'];        }        return 0;    }    public function listByName($name='', $order = '', $desc = false)    {        $where = "";        if ($name) {            $where = " where name like '%$name%'";        }        if ($order) {            $where .= " order by $order";            if ($desc) {                $where .= " desc";            } else {                $where .= " asc";            }        }        $sql = "select * from $this->tablename $where;";        $res = $this->select($sql);        return $res;    }    /**     * save     */    public function save($data)    {        $columns = "";        $values = "";        foreach ($data as $key => $value) {            $columns .=  "`" . $key . "`,";            $values .=  "'" . $value . "',";        }        $columns = rtrim($columns, ',');        $values = rtrim($values, ',');        $sql = "INSERT INTO `$this->tablename`(" . $columns . ") VALUES(". $values . ");";        return $this->exec($sql);    }        /**     * updateById     */    public function updateById($data)    {        $id = $data['id'];        unset($data['id']);        $columns = "";        foreach ($data as $key => $value) {            $columns .= "`" . $key . "`='" . $value ."',";        }        $columns = rtrim($columns, ',');        $sql = "UPDATE `$this->tablename` SET $columns WHERE `id`=$id";        return $this->exec($sql);    }    /**     * deleteByIds     */    public function deleteById($id)    {        $sql = "DELETE FROM `$this->tablename` WHERE `id` IN(";        if (is_array($id)) {            for ($i=0; $i < count($id); $i++) {                 $sql .= $id[$i] . ',';            }            $sql = rtrim($sql, ',');            $sql .= ");";        } else {            $sql = "DELETE FROM `$this->tablename` WHERE `id`=$id;";        }        return $this->exec($sql);    }    // public function __destruct()    // {    //     $this->query->close();    // }	function add($data){				//列名数组		$cols=array();		//列值数组		$vals=array();				foreach($data as $key=>$val){			$cols[]="`".$key."`"; 			$vals[]="'".$val."'";		}				//$cols=array(0=>'`titlekey`',1=>'`contentkey`'); //		//$vals=array(0=>"'titleval'",1=>"'contentval'"); //						//用","将数组每个元素重新拼接起来		$str_cols=implode(',',$cols);  //$str_cols=  `titlekey`,`contentkey` 		$str_vals=implode(',',$vals);  //$str_vals=  'titleval','contentval'				//执行插入数据		$sql="insert into ".$this->tablename."($str_cols) values($str_vals);";				return $this->getQuery()->insert($sql );	}			function update($data,$where){						$wherestr = '';		if(!empty($where)){			$wherestr .=' where '.$where;		}				$par_array=array();		foreach($data as $key=>$val){			$par_array[]="`".$key."`="."'".$val."'";		}				//用","将修改列和列值的数组里每个元素重新拼接起来		$param=implode(',',$par_array); 					$sql = "update ".$this->tablename." set ".$param." ".$wherestr." ";				return $this->getQuery()->query($sql);			}		function get_lists($where, $limit=''){				$wherestr = '';		if(!empty($where)){			$wherestr .=' where '.$where;		}		$sql = 'select * from '.$this->tablename.$wherestr . $limit;//		echo $sql;		return $this->getQuery()->select($sql);	}	function get_sum($where){		$wherestr = '';		if(!empty($where)){			$wherestr .=' where '.$where;		}				$sql = "select count(*) as sum from ".$this->tablename.$wherestr;				$data = $this->getQuery()->get_row($sql);				return $data['sum'];	}				function get_one($where){				$wherestr = '';		if(!empty($where)){			$wherestr .=' where '.$where;		}				$sql = "select * from ".$this->tablename.$wherestr;				//var_dump($sql);exit;				$data = $this->getQuery()->get_row($sql);				return $data;	}}
 |