Sysdb库类的封装

原创 2019-02-09 12:02:52 328
摘要:<?phpnamespace Util;use  think\Db;use think\db\Where;class  SysDb{    //指定表名    public function table($table)    {        $this->where

<?php

namespace Util;
use  think\Db;
use think\db\Where;

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 tiem()
   {
       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  count()
   {
       return Db::name($this->table)->where($this->where)->count();
   }

   //分页
   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-> $this->order && $query->order($this->order);
       $data=$query->paginate($pageSize,$total);
       return array('total'=>$total,'list'=>$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 updata($data)
   {
       return Db::name($this->table)->where($this->where)->update($data);
   }

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

批改老师:韦小宝批改时间:2019-02-11 10:04:27
老师总结:写的很不错 封装的数据库的操作类 基本上是可以重复使用的 在以后的其他项目中也可以直接拿过来使用哦!

发布手记

热门词条