ThinkPHP数据模型基类

2026-05-02 05:27:37 219
分类:php

thinkphp自定义数据模型基类。其他数据模型可继承自这个类。

基础版

<?php
namespace Common\Model;
use Think\Model;
header("Content-Type:text/html; charset=utf8");

/**
 * 基类数据模型
 */
class BaseModel extends Model
{
    //添加数据
    public function addData($data)
    {
        $id = $this->add($data);
        return $id;
    }

    //获取数据条数
    public function getCount($where = '')
    {
        $result = $this->where($where)->count();
        return $result;
    }

    //获取一条数据
    public function findData($where)
    {
        $result = $this->where($where)->find();
        return $result;
    }

    //获取所有数据
    public function selectData($where, $order = 'id asc', $limit = '')
    {
        $result = $this->where($where)->order($order)->limit($limit)->select();
        return $result;
    }

    //获取分页数据
    public function getPage($where, $order = 'id asc', $limit = 10, $rule = '')
    {
        $count = $this->where($where)->count();
        $page = new \Think\Page($count, $limit, $rule);
        $show = $page->show();
        $data = $this->where($where)->order($order)->limit($page->firstRow . ',' . $page->listRows)->select();
        return array ("data" => $data, "page" => $show);
    }

    //过滤字段
    public function fieldData($where, $field, $sepa = null)
    {
        $result = $this->where($where)->getField($field, $sepa);
        return $result;
    }

    //修改数据
    public function editData($where, $data)
    {
        $result = $this->where($where)->save($data);
        return $result;
    }

    //删除数据
    public function deleteData($where)
    {
        if (empty($where)) {
            die('where为空的危险操作');
        }
        $result = $this->where($where)->delete();
        return $result;
    }
}

未使用查询缓存版本

<?php    
// +----------------------------------------------------------------------    
// | Author: 栉风沐雨 <188150920@qq.com>    
// +----------------------------------------------------------------------    
// | File.class.php 创建时间:2017-07-01    
// | 最后修改时间:2018-07-19    
// +----------------------------------------------------------------------    
namespace Common\Model;    
use Think\Model;    
header("Content-Type:text/html; charset=utf8");    
/**    
 * 基类数据模型    
 */    
class BaseModel extends Model    
{    
    protected $cache = false;   //查询缓存,开启缓存后不要忘记关闭    
    protected $time = 3600;     //缓存时间    
    //设置缓存    
    public function setCache($bool = false, $time = 3600)    
    {    
        $this->cache = $bool;    
        $this->time = $time;    
        return $this;    
    }    
    //添加数据    
    public function addData($data)    
    {    
        $id = $this->add($data);    
        return $id;    
    }    
    //获取一条数据    
    public function findData($where)    
    {    
        $result = $this->where($where)->find();    
        return $result;    
    }    
    //获取所有数据(可缓存)    
    public function selectData($where, $order = 'id asc', $limit = '')    
    {    
        $result = $this->cache($this->cache, $this->time)->where($where)->order($order)->limit($limit)->select();    
        return $result;    
    }    
    //获取分页数据(可缓存)    
    public function getPage($where, $order = 'id asc', $limit = 10, $rule = '')    
    {    
        $count = $this->where($where)->count();    
        $page = new \Think\Page($count, $limit, $rule);    
        $show = $page->show();    
        $data = $this->cache($this->cache, $this->time)->where($where)->order($order)->limit($page->firstRow . ',' . $page->listRows)->select();    
        return array ("data" => $data, "page" => $show);    
    }    
    //获取数据项    
    public function getOneField($where, $field)    
    {    
        $result = $this->where($where)->getField($field);    
        return $result;    
    }    
    //修改数据    
    public function editData($where, $data)    
    {    
        $result = $this->where($where)->save($data);    
        return $result;    
    }    
    //删除数据    
    public function deleteData($where)    
    {    
        if (empty($where)) {    
            die('where为空的危险操作');    
        }    
        $result = $this->where($where)->delete();    
        return $result;    
    }    
    //检测满足条件的数据是否存在    
    public function checkData($where)    
    {    
        $count = $this->where($where)->count();    
        $result = $count > 0 ? 1 : 0;    
        return $result;    
    }    
    //获取数据条数    
    public function getCount($where = '')    
    {    
        $result = $this->where($where)->count();    
        return $result;    
    }    
    /**    
     * 批量更新(如果数据不存在就新增)    
     * @param array $data 需要更新的数据(数组)    
     * @param string $field 需要更新的字段,如果多个用","分开。    
     * @return boolean    
     */    
    public function saveAll($data, $field = "")    
    {    
        //例:saveAll(array(array('id'=>1,'list_order'=>9),array('id'=>2,'list_order'=>1)),'list_order')    
        //sql原生语句:    
        //$sql="INSERT INTO category (id, list_order) VALUES    
        //       (1, '1'),    
        //       (2, '2'),    
        //       (3, '3')    
        //       ON DUPLICATE KEY UPDATE list_order=VALUES(list_order);";    
        //$result = $this->execute($sql, true);    
        //return $result;    
        if (empty($data) || !is_array($data)) {    
            $this->error = L('_DATA_TYPE_INVALID_');    
            return false;    
        }    
        $keys = array();    
        $strdata = "";    
        //数据处理    
        foreach ($data as $k => $v) {    
            if (is_array($v)) {    
                $strdata .= $strdata ? ",('" . implode("','", $v) . "')" : "('" . implode("','", $v) . "')";    
                $keys || $keys = array_keys($v);    
            } else {    
                $strdata = "('" . implode("','", $data) . "')";    
                $keys = array_keys($data);    
                break;    
            }    
        }    
        $field || $field = $keys;    
        if (is_string($field)) {    
            $field = explode(",", $field);    
        }    
        $keys = "(`" . implode("`,`", $keys) . "`)";    
        $tableName=$this->getTableName();    
        $sql = "INSERT INTO " . $tableName . $keys . "VALUES" . $strdata . " ON DUPLICATE KEY UPDATE ";    
        $strkey = "";    
        foreach ($field as $k => $v) {    
            $strkey .= $strkey ? ",`" . $v . "`=VALUES(`" . $v . "`)" : "`" . $v . "`=VALUES(`" . $v . "`)";    
        }    
        $sql .= $strkey;    
        $result = $this->execute($sql, true);    
        return $result;    
    }    
}

使用查询缓存版本

设置合适的缓存时间,只有在高并发且不用实时更新的情况下用。也可以使用数据缓存或者静态缓存代替。

/**
 * 基类Model(调用缓存后记得还原)
 */
class BaseModel extends Model{
    protected $cache=false; //是否缓存
    protected $expire=3000; //缓存时间
    protected $field='';    //选择字段
    
    //设置缓存(为false不读取缓存,只限读取模型)
    public function setCache($cache=false,$expire=3000){
        $this->cache=$cache;
        $this->expire=$expire;
        return $this;
    }
    
    public function setField($field=''){
        $this->field=$field;
        return $this;
    }
    
    //检测满足条件的数据是否存在
    public function checkData($where){
        $count=$this->where($where)->count();
        $result=$count>0?1:0;
        return $result;
    }
    
    //获取数据条数
    public function getCount($where=''){
        $result=$this->where($where)->count();
        return $result;
    }
    
    //添加数据
    public function addData($data){
        $id=$this->add($data);
        return $id;
    }
    
    //获取一条数据
    public function findData($where){
        $result=$this->cache($this->cache,$this->expire)->where($where)->find();
        return $result;
    }
    
    //获取所有数据
    public function selectData($where,$order='id asc',$limit=''){
        $result=$this->where($where)->cache($this->cache,$this->expire)->order($order)->limit($limit)->select();
        return $result;
    }

    //获取分页数据(可缓存)
    public function getPage($where,$order='id asc',$limit=10,$rule=''){
        $count=$this->getCount($where);
        $page = new \Think\Page($count,$limit,$rule);
        $show = $page->show();
        $data = $this->cache($this->cache,$this->expire)->field($this->field)->where($where)->order($order)->limit($page->firstRow.','.$page->listRows)->select();
        return array("data"=>$data,"page"=>$show);
    }
    
    //ajax获取分类
    public function getPageAjax($where,$order='id asc',$limit=''){
        $data = $this->where($where)->order($order)->limit($limit)->select();
        return $data;
    }
    
    //获取数据项
    public function getOneField($where,$field){
        $result=$this->where($where)->cache($this->cache,$this->expire)->getField($field);
        return $result;
    }
    
    //修改数据
    public function editData($where,$data){
        $result=$this->where($where)->save($data);
        return $result;
    }

    //删除数据
    public function deleteData($where){
        if (empty($where)) {die('where为空的危险操作');}
        $result=$this->where($where)->delete();
        return $result;
    }

    /**
     * 批量更新(如果数据不存在就新增)
     * @param array $data 需要更新的数据(数组)
     * @param string $field 需要更新的字段,如果多个用","分开。
     * @return boolean
     */
    public function saveAll($data, $field = "") {
        //例:saveAll(array(array('id'=>1,'list_order'=>9),array('id'=>2,'list_order'=>1)),'list_order')
        //sql原生语句:
        //$sql="INSERT INTO category (id, list_order) VALUES 
        //       (1, '1'), 
        //       (2, '2'), 
        //       (3, '3') 
        //       ON DUPLICATE KEY UPDATE list_order=VALUES(list_order);";
        //$result = $this->execute($sql, true);
        //return $result;
        
        if (empty($data) || !is_array($data)) {
            $this->error = L('_DATA_TYPE_INVALID_');
            return false;
        }
        $keys = array();
        $strdata = "";
        //数据处理
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $strdata.=$strdata ? ",('" . implode("','", $v) . "')" : "('" . implode("','", $v) . "')";
                $keys || $keys = array_keys($v);
            } else {
                $strdata = "('" . implode("','", $data) . "')";
                $keys = array_keys($data);
                break;
            }
        }
        $field || $field = $keys;
        if (is_string($field)) {
            $field = explode(",", $field);
        }
        $keys = "(`" . implode("`,`", $keys) . "`)";
        $sql = "INSERT INTO " . $this->trueTableName . $keys . "VALUES" . $strdata . " ON DUPLICATE KEY UPDATE ";
        $strkey = "";

        foreach ($field as $k => $v) {
            $strkey.=$strkey ? ",`" . $v . "`=VALUES(`" . $v . "`)" : "`" . $v . "`=VALUES(`" . $v . "`)";
        }
        $sql.=$strkey;
        $result = $this->execute($sql, true);
        return $result;
    }
}