自己手动编写数据库访问类SysDb
<?php
/**
* Created by PhpStorm.
* User: Jason
* Date: 2019/4/29
* Time: 7:25
*/
namespace Util;
use think\Db;
// 数据库操作类
class SysDb
{
// 是否建立连接标志
public static $instance = null;
// 封装静态方法调用
public static function getnstance($table)
{
// 如果连接为空,则创建连接 好像这样有问题
//if(self::$instance == null) {
//self::$instance = self::table($table);
//}
//return self::$instance;
// 静态方法调用,不需要实例化
return self::table($table);
}
// 表名
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);
// 如果有limit 并查询
$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 $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 ['total'=>$total,'lists'=>$data->items(),'pages'=>$data->render()];
}
// 单条数据写入
public function insert($data)
{
// 写入并返回主键ID
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);
}
}