实现数据库访问类封装

Original 2019-05-15 16:27:24 334
abstract:由于thinkphp5.1的数据库访问类方法较多,我们并用不到那么多,防止对数据库产生过多的访问,自己编写数据库访问方法:<?php /**  * Created by PhpStorm.  * User: Administrator  * Date: 2019/5/15  *&nb

由于thinkphp5.1的数据库访问类方法较多,我们并用不到那么多,防止对数据库产生过多的访问,自己编写数据库访问方法:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/15
 * Time: 16:08
 */
namespace Util;
use think\Db;

class SysDb {
    public function table($table){
        $this->where = [];
        $this->field = '*';
        $this->order = '';
        $this->limit = 0;

        $this->table = $table;
        return $this;
    }

    public function field($field){
        $this->field = $field;
        return $this;
    }

    public function limit($limit){
        $this->limit = $limit;
        return $this;
    }

    public function order($order){
        $this->order = $order;
        return $this;
    }

    public function where($where){
        $this->where = $where;
        return $this;
    }

    // 返回一条记录
    public function item(){
        return Db::name($this->table)->field($this->field)->where($this->where)->find();
    }

    // 返回多条数据
    public function lists(){
        $query = Db::name($this->table)->field($this->field)->where($this->where);
        $this->limit && $query = $query->limit($this->limit);
        $this->order && $query = $query->order($this->order);
        return $query->select();
    }

    // 自定义索引
    public function cates($index){
        $query = Db::name($this->table)->field($this->field)->where($this->where);
        $this->limit && $query = $query->limit($this->limit);
        $this->order && $query = $query->order($this->order);
        $lists = $query->select();
        if(!$lists){
            return $lists;
        }
        $result = [];
        foreach ($lists as $key => $value) {
            $result[$value[$index]] = $value;
        }
        return $result;
    }

    //分页
    public function pages($pageSize=10){
        $total=Db::name($this->table)->where($this->where)->count();
        $query = Db::name($this->table)->field($this->field)->where($this->where);
        $this->order && $query = $query->order($this->order);
        $data = $query->paginate($pageSize,$total);
        return array('total'=>$total,'lists'=>$data->items(),'pages'=>$data->render());
    }

    public function insert($data){
        return Db::name($this->table)->insertGetId($data);
    }

    // 批量添加数据
    public function insertAll($data){
        return Db::name($this->table)->insertAll($data);
    }

    // 修改
    public function update($data){
        return Db::name($this->table)->where($this->where)->update($data);
    }

    // 删除
    public function delete(){
        return Db::name($this->table)->where($this->where)->delete();
    }

}


Correcting teacher:查无此人Correction time:2019-05-16 09:21:46
Teacher's summary:完成的不错。自己封装,条件要多判断,防止别人传值注入。继续加油。

Release Notes

Popular Entries