MVC之路---實(shí)現(xiàn)ORM

我們在tp等框架經(jīng)常用到ORM操作數(shù)據(jù)庫,例如

$user->where(['username'=>'chen'])->select();

像這種不需要寫原生sql就能得到想要的結(jié)果到底是什么實(shí)現(xiàn)的呢,最近手寫了一個ORM類,是初稿,基于mysqli擴(kuò)展實(shí)現(xiàn),當(dāng)然,大家都知道框架都是用pdo擴(kuò)展,用到適配器模式等,以后有時間我都會一一實(shí)現(xiàn),目前僅支持mysql,類代碼如下(還有很多地方需要完善,初稿)

<?php
namespace library;
/*
 * 數(shù)據(jù)庫操作類
 * author jinanAv 2019年9月3日11:36:01
 */

class Db
{
    private static $selfObj = null;
    //數(shù)據(jù)庫連接池
    protected $conn;
    //sql語句
    protected $sql;
    //最后生成的sql
    protected $lastSql = null;
    //日志目錄
    protected $logDir = './log/';
    //日志開關(guān)
    protected $logOpen = true;
    //調(diào)試模式
    protected $debug = false;
    //錯誤提示(不開啟調(diào)試模式時使用)
    protected $errorTip = 'Params Error';
    //選擇需要操作的表
    protected $table;
    //記錄表結(jié)構(gòu)信息
    protected $describe = [];
    //主鍵
    protected $pk = null;
    //表別名
    protected $alias = '';
    //設(shè)置排序參數(shù)
    protected $orderParam = '';
    //設(shè)置查詢字段
    protected $fieldParam = '*';
    //查詢條件參數(shù)
    protected $whereParam = '';
    //條件參數(shù)數(shù)組
    protected $whereParamArray = [];
    //允許查詢條數(shù)
    protected $limitParam = '';
    //分組字段參數(shù)
    protected $groupParam = '';
    //鏈表參數(shù)
    protected $joinParam = '';
    //數(shù)據(jù)參數(shù)
    protected $dataParam = [];
    //更新參數(shù)
    protected $updateParam = '';
    //生成sql而不執(zhí)行
    protected $fetchSql = false;
    //數(shù)據(jù)庫鏈接信息
    protected $connInfo = [
        'host' => '127.0.0.1',
        'user' => 'root',
        'password' => 'root',
        'database' => 'edusoho',
        'prefix' => '',
        'charset' => 'uft8mb4'
    ];

    /**
     * 應(yīng)用初始化
     * @author jinanav 2019年9月3日12:07:15
     * @param array $connInfo 連接參數(shù)
     * @param bool $debug 是否開啟調(diào)試
     * @return $this;
     */
    public static function init($connInfo = [],$debug = false){
        if(empty(self::$selfObj)){
            self::$selfObj = new static();
            //配置數(shù)據(jù)庫連接參數(shù)
            !empty($connInfo) && self::$selfObj->connInfo = array_merge(self::$selfObj->connInfo,$connInfo);
            //是否開啟debug
            self::$selfObj->debug($debug);
            //連接數(shù)據(jù)庫
            self::$selfObj->connect(self::$selfObj->connInfo,false);
            //返回操作對象
        }
        return self::$selfObj;
    }

    /**
     * 更換數(shù)據(jù)表
     * @author jinanav 2019年9月1日16:34:48
     * @param string $table 數(shù)據(jù)表名
     * @return $this
     */
    public static function table($table){
        empty(self::$selfObj) && self::init();
        self::$selfObj->table = $table;
        self::$selfObj->getPk();
        return self::$selfObj;
    }

    /**
     * 更換數(shù)據(jù)表,自動補(bǔ)充前綴
     * @author jinanav 2019年9月1日16:34:22
     * @param string $name 數(shù)據(jù)表名
     * @return $this|object
     */
    public static function name($name){
        empty(self::$selfObj) && self::init();
        return self::table(self::$selfObj->connInfo['prefix'].$name);
    }

    /**
     * 鏈接數(shù)據(jù)庫
     * @author jinanav 2019年9月3日12:07:15
     * @param array $data 插入數(shù)據(jù)集
     * @return object|bool;
     */
    public function connect($connInfo = [],$isReturn = true){
        try{
            $this->conn = @mysqli_connect($connInfo['host'],$connInfo['user'],$connInfo['password'],$connInfo['database']);
            if(!$this->conn){
                $this->debug ? exit(mysqli_connect_error()) : exit('數(shù)據(jù)庫連接失敗');
            }
            mysqli_query($this->conn,'SET NAMES '.$connInfo['charset']);
            if(!$isReturn) return true;
            return $this;
        }catch (\Exception $e){
            $this->debug ? exit($e->getMessage()) : exit($this->errorTip);
        }
    }

    /**
     * 日志開關(guān)
     * @author jinanav 2019年9月3日12:07:15
     * @param array $data 插入數(shù)據(jù)集
     * @return object|bool;
     */
    public function setLog($swith = false){
        $this->logOpen = $swith;
    }

    /**
     * 日志寫入
     * @author jinanav 2019年9月16日12:12:35
     * @param string $msg 日志內(nèi)容
     * @return array|bool;
     */
    public function log($msg){
        try{
            !is_dir($this->logDir) && exit('The log root directory does not exist. Please create it manually');
            $fileDir = $this->logDir.date('Ym');
            $fileName = $fileDir.'/'.date('d').'.log';
            !file_exists($fileName) && mkdir($fileDir,0777,true);
            $contents = '【'.date('Y-m-d H:i:s').'】'.PHP_EOL;
            $contents = $contents.'|------------------------------------------|'.PHP_EOL;
            $contents = $contents.'【SQL】'.$this->sql.PHP_EOL;
            $contents = $contents.'【MSG】:'.$msg.PHP_EOL;
            $contents = $contents.'|------------------------------------------|'.PHP_EOL.PHP_EOL.PHP_EOL;
            file_put_contents($fileName,$contents.PHP_EOL,FILE_APPEND);
        }catch (\Exception $e){
            $this->debug && exit($e->getMessage());
        }

    }

    /**
     * 單條數(shù)據(jù)插入
     * @author jinanav 2019年9月1日16:33:14
     * @param array $data 插入數(shù)據(jù)集
     * @return array|bool;
     */
    public function insert(array $data = []){
        !empty($data) && $this->dataParam = array_merge($this->dataParam,$data);
        $sqls = 'insert into %s (%s) values(%s)';
        $k = $v = "";
        foreach ($this->dataParam as $key => $value) {
            $k .= "$key,";
            $v .= '"'.$value.'",';
        }
        $k = rtrim($k,",");
        $v = rtrim($v,",");
        $this->sql = sprintf($sqls,$this->table,$k,$v);
        return $this->result();
    }

    /**
     * 批量數(shù)據(jù)插入
     * @author jinanav 2019年9月1日16:33:49
     * @param array $data 插入數(shù)據(jù)集
     * @return array|bool;
     */
    public function insertAll(array $data = []){
        !empty($data) && $this->dataParam = array_merge($this->dataParam,$data);
        $sqls = 'INSERT IGNORE INTO %s (%s) values %s';
        $k = $v = "";
        foreach ($this->dataParam[0] as $key => $value) {
            $k .= "$key,";
        }
        foreach ($this->dataParam as $key => $value) {
            foreach ($value as $kk => $vv) {
                $this->dataParam[$key][$kk] = '"'.$vv.'"';
            }
            $values = implode(',', $this->dataParam[$key]);
            $v .= '('.$values.'),';
        }
        $k = rtrim($k,",");
        $v = rtrim($v,",");
        $this->sql = sprintf($sqls,$this->table,$k,$v);
        return $this->result();
    }

    /**
     * 刪除數(shù)據(jù)
     * @author jinanav 2019年9月18日16:06:31
     * @param int $id 主鍵id
     * @return bool;
     */
    public function delete($id = null){
        !empty($id) && $this->whereParam = ' where '.$this->pk.' = '.$id;
        empty($this->whereParam) && exit('Missing delete condition');
        $this->sql = 'delete from '.$this->table.$this->whereParam;
        return $this->result();
    }

    /**
     * 別名
     * @author jinanav 2019年9月17日16:11:05
     * @param string $name 表別名
     * @return $this
     */
    public function alias($name){
        $this->alias = $name;
        $this->table = $this->table.' as '.$this->alias;
        return $this;
    }

    /**
     * 鏈表
     * @author jinanav 2019年9月1日16:33:49
     * @param string $joinTable 鏈表名
     * @param string $condition 鏈表規(guī)則
     * @param string $type 鏈表類型
     * @return $this|object
     */
    public function join($joinTable,$condition,$type = 'inner'){
        $this->joinParam = $type.' join '.$joinTable.' on '.$condition;
        empty($this->alias) && exit('Table '.$this->table.' missing alias');
        return $this;
    }

    /**
     * 左鏈表
     * @author jinanav 2019年9月1日16:33:49
     * @param string $joinTable 鏈表名
     * @param string $condition 鏈表規(guī)則
     * @return $this|object
     */
    public function leftJoin($joinTable,$condition){
        return $this->join($joinTable,$condition,'left');
    }

    /**
     * 右鏈表
     * @author jinanav 2019年9月1日16:33:49
     * @param string $joinTable 鏈表名
     * @param string $condition 鏈表規(guī)則
     * @return $this|object
     */
    public function rightJoin($joinTable,$condition){
        return $this->join($joinTable,$condition,'right');
    }


    /**
     * 設(shè)置排序參數(shù)
     * @author jinanav 2019年9月2日22:24:54
     * @param string $order 排序參數(shù)字符串
     * @return $this
     */
    public function order($order){
        $this->orderParam = 'order by '.$order;
        return $this;
    }

    /**
     * 字段自增
     * @author jinanav 2019年9月18日16:06:31
     * @param string $field 字段
     * @param string $step  增長步長
     * @return bool;
     */
    public function setInc($field,$step = 1){
        $this->updateParam = $field.'='.$field.'+'.$step;
        return $this->update();
    }

    /**
     * 字段自減
     * @author jinanav 2019年9月18日16:39:53
     * @param string $field 字段
     * @param string $step  增長步長
     * @return bool;
     */
    public function setDec($field,$step = 1){
        $this->updateParam = $field.'='.$field.'-'.$step;
        return $this->update();
    }
    /**
     * 返回查詢
     * @author jinanav 2019年9月1日16:27:06
     * @param array $data 查詢條件集
     * @return array|bool;
     */
    public function select(){
        return $this->dealResult();
    }

    /**
     * 根據(jù)主鍵獲取數(shù)據(jù)
     * @author jinanav 2019年9月3日12:21:27
     * @param array $pk 主鍵值
     * @return array;
     */
    public function get($pk){
        $this->where([$this->pk => intval($pk)]);
        return $this->find();
    }

    /**
     * 返回查詢(單條數(shù)據(jù))
     * @author jinanav 2019年9月1日16:27:48
     * @param array $data 查詢條件集
     * @return array|bool;
     */
    public function find(){
        $info = $this->dealResult();
        if(is_array($info)){
            return $info[0];
        }
        return $info;
    }

    /**
     * 返回單列查詢
     * @author jinanav 2019年11月1日17:52:47
     * @param string $field 列字段
     * @return array|bool;
     */
    public function column($field){
        $list = $this->select();
        if(!is_array($list)) return $list;
        if(strpos($field,',') !== false ){
            $newArray = [];
            $args = explode(',',$field);
            if(count($args) == 2){
                foreach ($list as $key => $value){
                    $newArray[$value[$args[0]]] = $value[$args[1]];
                }
            }else{
                foreach ($list as $key => $value){
                    $newArray[$value[$args[0]]] = $value;
                }
            }
            return $newArray;
        }
        return array_column($list,$field);
    }
    /**
     * 設(shè)置查詢字段
     * @author jinanav 2019年9月2日22:13:17
     * @param array $filed 需要查詢的字段
     * @return $this
     */
    public function field($filed = '*'){
        $this->fieldParam = $filed;
        return $this;
    }

    /**
     * 統(tǒng)計(jì)查詢條數(shù)
     * @author jinanav 2019年9月2日22:13:17
     * @param string $filed 需要查詢的字段
     * @return int;
     */
    public function count($field = '*'){
        $this->sql = "select count($field) as av_count from ".$this->table.' '.$this->whereParam;
        $result = $this->find();
        return intval($result['av_count']);
    }

    /**
     * 列求和
     * @author jinanav 2019年9月16日14:09:46
     * @param string $filed 需要求和的字段
     * @return int;
     */
    public function sum($field){
        $this->sql = "select sum($field) as av_sum from ".$this->table.' '.$this->whereParam;
        $result = $this->find();
        return ($result['av_sum']);
    }

    /**
     * 最大值
     * @author jinanav 2019年9月16日14:47:26
     * @param string $filed 求最大值字段
     * @return int;
     */
    public function max($field){
        $this->sql = "select max($field) as av_max from ".$this->table.' '.$this->whereParam;
        $result = $this->find();
        return ($result['av_max']);
    }

    /**
     * 最小值
     * @author jinanav 2019年9月16日14:47:26
     * @param string $filed 求最小值字段
     * @return int;
     */
    public function min($field){
        $this->sql = "select min($field) as av_min from ".$this->table.' '.$this->whereParam;
        $result = $this->find();
        return ($result['av_min']);
    }

    /**
     * 平均值
     * @author jinanav 2019年9月16日14:50:32
     * @param string $filed 求最大值字段
     * @param int $reserve 保留兩位小數(shù)
     * @return double;
     */
    public function avg($field,$reserve = 2){
        $this->sql = "select round(avg($field),$reserve) as av_avg from ".$this->table.' '.$this->whereParam;
        $result = $this->find();
        return doubleval($result['av_avg']);
    }

    /**
     * 分組
     * @author jinanav 2019年9月16日14:50:32
     * @param string $filed 分組字段
     * @return $this
     */
    public function group($filed){
        $this->groupParam = 'group by '.$filed;
        return $this;
    }

    /**
     * 獲取主鍵以及表結(jié)構(gòu)
     * @author jinanav 2019年9月3日10:53:34
     * @param array $filed 需要查詢的字段
     * @return bool;
     */
    public function getPk(){
        $result = mysqli_query($this->conn,'describe '.$this->table);
        if($result){
            while( $row=mysqli_fetch_array($result)){
                $row['Key'] =='PRI' && $this->pk = $row['Field'];
                $this->describe[] = $row['Field'];
            }
        }else{
            $this->logOpen && $this->log($this->error());
            $this->debug ? exit($this->error()) : exit($this->errorTip);
        }
        return true;
    }

    /**
     * 數(shù)據(jù)準(zhǔn)備
     * @author jinanav 2019年9月17日17:00:05
     * @param array $data 準(zhǔn)備數(shù)據(jù)參數(shù)
     * @return $this
     */
    public function data(array $data){
        $this->dataParam = $data;
        return $this;
    }

    /**
     * 數(shù)據(jù)更新
     * @author jinanav 2019年7月20日11:25:37
     * @param array $data 更新數(shù)據(jù)
     * @return bool;
     */
    public function update(array $data = []){
        !empty($data) && $this->dataParam = array_merge($this->dataParam,$data);
        if(!empty($this->dataParam)){
            if(count($this->dataParam) != count($this->dataParam,1)){
                exit('Only one-dimensional array updates are supported');
            }
            $upString = '';
            foreach ($this->dataParam as $key => $value){
                $upString .= $key  .' = "'.$value.'",';
            }
            $this->updateParam = rtrim($upString,',');
            if(in_array($this->pk,array_keys($this->dataParam)) && empty($this->whereParam)){
                $this->whereParam = 'where '.$this->pk.' = "'.$this->dataParam[$this->pk].'"';
            }
        }
        empty($this->updateParam) && exit('Missing update field');
        empty($this->whereParam) && exit('Missing update condition');
        $this->sql = 'update '.$this->table.' set '.$this->updateParam.' '.$this->whereParam;
        return $this->result();
    }


    /**
     * 處理查詢數(shù)據(jù)集
     * @author jinanav 2019年7月20日11:25:37
     * @param int $team_id 活動id
     * @param string $choose_time 活動時間
     * @return array|bool;
     */
    public function dealResult(){
        $array = [];
        $result = $this->result();
        if($this->fetchSql) return $result;
        if($result){
            while ($row = mysqli_fetch_assoc($result)) {
                $array[] = $row;
            }
            if(!empty($array)) return $array;
        }
        return null;
    }

    /**
     * 設(shè)置查詢/更新參數(shù)
     * @author jinanav 2019年9月1日16:36:22
     * @param string|array $filed 字段參數(shù)
     * @param string $op 表達(dá)式
     * @param string $value 字段值
     * @param string $option 額外參數(shù)
     * @return $this
     */
    public function where($filed,$op = '=',$value = null,$option = 'and'){
        if(!is_array($filed)) {
            if(empty($value)){
                $this->whereParam = 'where '.'"'.$filed.'" ';
            }else{
                if($op == 'in'){
                    $this->whereParamArray[] = $option.' '.$filed.' '.$op.' ('.$value.')';
                }else{
                    $this->whereParamArray[] = $option.' '.$filed.' '.$op.' "'.$value.'"';
                }
            }
        }else{
            $string = '';
            foreach ($filed as $k => $v){
                $string .= ' '.$k.'='.'"'.$v.'"'.' '.$option;
                if(empty($this->joinParam) && !in_array($k,$this->describe)){
                    $this->debug ? exit('Nonexistent field '.$k) : exit($this->errorTip);
                }
            }
            $this->whereParam = ' where '.rtrim($string,$option);
        }
        return $this;
    }

    /**
     * OR查詢
     * @author jinanav 2019年9月1日16:36:22
     * @param string|array $filed 字段參數(shù)
     * @param string $op 表達(dá)式
     * @param string $value 字段值
     * @return $this
     */
    public function whereOr($filed,$op,$value){
        return $this->where($filed,$op,$value,'or');
    }

    /**
     * OR查詢
     * @author jinanav 2019年9月1日16:36:22
     * @param string|array $filed 字段參數(shù)
     * @param string $value 字段值
     * @param string $option 額外參數(shù)
     * @return $this
     */
    public function whereIn($filed,$value,$option = 'and'){
        return $this->where($filed,'in',is_array($value) ? implode(',',$value) : $value,$option);
    }


    /**
     * 獲取最后生成的sql
     * @author jinanav 2019年9月2日21:49:09
     * @return string;
     */
    public function getLastSql(){
        return $this->lastSql;
    }

    /**
     * 直接執(zhí)行原生的sql
     * @author jinanav 2019年9月3日12:12:27
     * @param string $sql 原生sql
     * @return mixed;
     */
    public function query($sql){
        $this->sql = $sql;
        if(strpos(strtolower($this->sql),'select')) return $this->select();
        return $this->result();
    }

    /**
     * 生成最后的sql
     * @author jinanav 2019年9月2日22:12:40
     * @return $this
     */
    public function fetchSql(){
        $this->fetchSql = true;
        return $this;
    }

    /**
     * MySQL limit 處理
     * @author jinanav 2019年9月3日16:23:09
     * @param int $start 開始位置
     * @param int $length 查詢條數(shù)
     * @return $this
     */
    public function limit($start,$length = null){
        if (is_null($length) && strpos($start, ',')) {
            list($start, $length) = explode(',', $start);
        }
        $this->limitParam= 'limit '.intval($start) . ($length ? ',' . intval($length) : '');
        return $this;
    }

    /**
     * 生成最后where語句
     * @author jinanav 2019年9月2日22:12:40
     * @return string;
     */
    public function buildWhere(){
        $where = '';
        foreach ($this->whereParamArray as $value){
            $where.= $value;
        }
        !empty($this->whereParam) ? $this->whereParam .= $where : $this->whereParam = 'where '.ltrim(ltrim($where,'and'),'or');
        return true;
    }

    /**
     * 生成最后的sql
     * @author jinanav 2019年9月2日22:12:40
     * @return string;
     */
    public function buildSql(){
        !empty($this->whereParamArray) && $this->buildWhere();
        empty($this->sql) && empty($this->table) && exit('no table to select');
        empty($this->pk) && !empty($this->table) && exit('Please set the primary key of the data table');
        empty($this->orderParam) && empty(trim($this->joinParam)) && $this->orderParam = 'order by '.$this->pk.' desc';
        empty($this->orderParam) && !empty(trim($this->alias)) && empty($this->orderParam) && $this->orderParam = 'order by '.$this->alias.'.'.$this->pk.' desc';
        !empty($this->groupParam) && $this->orderParam = '';//兼容group by
        empty($this->sql) && $this->sql = 'select '.$this->fieldParam.' from '.$this->table.' '.$this->joinParam.' '.$this->whereParam.' '.$this->groupParam.' '.$this->orderParam.' '.$this->limitParam;
    }

    /**
     * 是否開啟debug
     * @author jinanav 2019年9月2日21:49:41
     * @param bool $debug 是否開啟debug
     * @return bool;
     */
    public function debug($debug){
        $this->debug = $debug;
    }


    /**
     * 分頁實(shí)現(xiàn)
     * @author jinanav 2019年10月30日22:42:56
     * @param int $offset 每頁顯示條數(shù)
     * @param string $type 分頁類型
     * @return bool;
     */
    public function page($offset = 15,$type = 'get'){
        $result['list'] = $this->select();
        $result['totalPage'] = ceil($this->count() / $offset);
        $result['currPage'] = $_GET['page'];//Helper::input('get.page');
        $result['limit'] = $offset;
        if($type == 'get') {
            $result['pageHref'] = new Pagination($result['totalPage']);
        }
        return $result;
    }

    /**
     * 返回執(zhí)行時的錯誤信息
     * @author jinanav 2019年9月2日21:49:41
     * @return bool;
     */
    public function error(){
        return mysqli_error($this->conn);
    }

    /**
     * 執(zhí)行sql
     * @author jinanav 2019年9月2日21:50:11
     * @return mixed;
     */
    public function result(){
        $this->buildSql();
        if($this->fetchSql) return $this->sql;
        try{
            $info = mysqli_query($this->conn,$this->sql);
            if($info === false){
                $this->logOpen && $this->log($this->error());
                $this->debug && exit($this->error());
            }
            $this->clear();
            return $info;
        }catch (\Exception $e){
            $errorMsg = '<h1>'.$this->error().'</h1>><br>'.$e->getMessage();
            $this->logOpen && $this->log($errorMsg);
            $this->debug && exit($errorMsg);
            return false;
        }
    }


    /**
     * 清理sql
     * @author jinanav 2019年9月2日21:50:37
     * @return ;
     */
    public function clear(){
        $array = ['sql','alias','orderParam','fieldParam',
            'whereParam','whereParamArray','limitParam','joinParam','dataParam','updateParam'];
        foreach ($array as $value){
            is_array($this->$value) ? $this->$value = [] : $this->$value = '';
        }
    }

    /**
     * 關(guān)閉數(shù)據(jù)庫鏈接
     * @author jinanav 2019年9月2日21:50:37
     * @return mixed;
     */
    public function closeConn(){
        @mysqli_close($this->conn);
    }

    /**
     * 未完成的函數(shù)提示
     * @author jinanav 2019年9月16日16:04:19
     * @return mixed;
     */
    public function __call($name, $arguments){
        exit('function '.$name.' is underFind,But the author will try to improve it and Thank you for your support');
    }

    /**
     * 對象回收時關(guān)閉數(shù)據(jù)庫鏈接
     */
    public function __destruct(){
        $this->closeConn();
    }

}

使用如下(載入方式自行處理,如果直接用require 去掉Db類的namespace 直接使用)

<?php
require_once 'library/autoload.php';
use library\Db;
$db = new Db();
$db->debug(true);
$db->setLog(true);
//或者 $db = new Db([],true,true);
$data = [];
for ($i=300;$i<350;$i++){
    $array['uid'] = $i.rand(100,999);
    $array['contents'] = time().$i.rand(1000,9999);
    $data[] = $array;
}

$list = $db->name('apply_log')->field('id,uid')->where('id','>',200)->where('id','<=',204)
            ->whereOr('uid','=',424)->select();
var_dump($list);

exit();
//單條插入
$result = $db->name('apply_log')->data($array)->insert();
//或者 $db->name('apply_log')->insert($array)
var_dump($result);
echo '<br>';


//批量插入
$result = $db->name('apply_log')->data($data)->insertAll();
//或者 $db->name('apply_log')->insertAll($data);
var_dump($result);
echo '<br>';


//數(shù)據(jù)更新
$result = $db->name('apply_log')->where(['id'=>211])->update(['contents'=>'測試測試']);
//或者數(shù)組中含主鍵 $db->name('apply_log')->update(['contents'=>'我就是測試','id'=>211]);
/*字段自增*/
$list = $db->name('apply_log')->where(['id'=>211])->setInc('uid');
/*字段自減*/
$list = $db->name('apply_log')->where(['id'=>211])->setDec('uid',125);
var_dump($result);
echo '<br>';

//數(shù)據(jù)查詢
/*根據(jù)主鍵查詢*/
$list = $db->name('apply_log')->get(211);
/*根據(jù)條件查詢單挑數(shù)據(jù),限定字段*/
$list = $db->name('apply_log')->field('create_time')->where(['id'=>211])->find();
/*根據(jù)條件查詢多條數(shù)據(jù)*/
$list = $db->name('apply_log')->where(['uid'=>349])->select();
/*limit查詢*/
$list = $db->name('apply_log')->where(['uid'=>349])->limit(2)->select();
/*order 查詢*/
$list = $db->name('apply_log')->where(['uid'=>349])->limit(2)->order('create_time asc')->select();
/*IN 查詢*/
$list = $db->name('apply_log')->field('id,uid')->whereIn('id',[201,203])->select();
/*復(fù)合查詢*/
$list = $db->name('apply_log')->field('id,uid')->where('id','>',200)->where('id','<=',204)
    ->whereOr('uid','=',424)->select();
/*group 查詢*/
$list = $db->name('apply_log')->field('uid')->group('uid')->select();
/*max 查詢*/
$list = $db->name('apply_log')->max('id');
/*min 查詢*/
$list = $db->name('apply_log')->min('id');
/*avg 查詢*/
$list = $db->name('apply_log')->avg('id');
/*sum 查詢*/
$list = $db->name('apply_log')->sum('id');
/*count 查詢*/
$list = $db->name('apply_log')->count();

/*join 查詢*/
$list = $db->name('activity_apply')->alias('a')->field('a.*,b.nick_name')
        ->join('travel_user b','a.uid=b.id')->where(['a.uid'=>16])->select();

/*leftJoin 查詢*/
$list = $db->name('activity_apply')->alias('a')->field('a.*,b.nick_name')
    ->leftJoin('travel_user b','a.uid=b.id')->where(['a.uid'=>16])->select();

/*rightJoin 查詢*/
$list = $db->name('activity_apply')->alias('a')->field('a.*,b.nick_name')
    ->rightJoin('travel_user b','a.uid=b.id')->where(['a.uid'=>16])->select();

/*delete 刪除數(shù)據(jù)*/
$list = $db->name('apply_log')->delete(210);
$list = $db->name('apply_log')->where(['id'=>202])->delete();

效果

image.png
通過簡單的ORM實(shí)現(xiàn) 我們可以進(jìn)一步思考,route,request,response,behavior,validate,middleware等等是如何實(shí)現(xiàn)以及調(diào)度。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、框架概述 課程概述 laravel 4天(之前TP框架還是很大的區(qū)別)(國外框架) 在線教育平臺 6天(lar...
    8d1b8e6a76e0閱讀 254評論 0 0
  • 一、框架概述 課程概述 laravel 4天(之前TP框架還是很大的區(qū)別)(國外框架) 在線教育平臺 6天(lar...
    大大的世界小小的夢想_97ef閱讀 1,397評論 0 2
  • 1. 一、框架概述 2. 課程概述 laravel 4天(之前TP框架還是很大的區(qū)別)(國外框架) 在線教育平臺 ...
    jim1999閱讀 375評論 0 0
  • 一、框架概述 課程概述 laravel 4天(之前TP框架還是很大的區(qū)別)(國外框架) 在線教育平臺 6天(lar...
    我愛開發(fā)閱讀 1,515評論 0 5
  • 文/徐家三姑娘 “—— 當(dāng)沉浸在文字的世界里,才發(fā)覺歲月靜好,幸福安寧。舍不得放棄手中的筆,也不會放棄手中的筆。 ...
    徐小燕XUXIAOYAN閱讀 344評論 2 7

友情鏈接更多精彩內(nèi)容