ci公共模型类
我们都知道,操作数据库的方法都写在模型中。但是一般情况下,一张表往往至少对应4个操作,也就是所谓crud。那么如果20张表,所对应的模型方法,就达到了80个,重复的操作显然这已经是一个体力活儿。
那么就对单表操作时,我们进行一下简单的封装。如下是ci框架的示例:
<?php
/**
* Created by PhpStorm.
* User: kangjianrong
* Date: 16-8-26
* Time: 上午10:29
*/ class My_model extends CI_Model {
//数据库
public $errors = array();
const dataBase = 'qndnew'; public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
/**
* 查询分页数据(使用于简单的单表操作)
* @param string $model 模型 例如:User_model
* @param string $table 表名
* @param string $select_fields 要显示字段
* @param array $param 查询条件:
* compare(比较):
* array($key => $val) $key为要操作的字段,$val为要操作的值
* array('name !=' => $name, 'id <' => $id, 'date >' => $date);
* like(模糊查询)
* array('title' => $match, 'page1' => $match, 'page2' => $match)
* customStr(自定义字符串):
* "name='Joe' AND status='boss' OR status='active'"
* in:
* array('userName' => array('Frank', 'Todd', 'James'))
* @param string $page 当前页数(查询全部数据时,设置为空)
* @param string $limit 查询条数(查询全部数据时,设置为空)
* @param array $order 排序条件:
* array($key => $val)
* $key为排序依据的字段,
* $val为排序的方式【asc (升序,默认)或 desc(降序), 或 random(随机)】
* @$isReturnCount boole 是否返回总条数
* @return array|boolean
*
*/
public function pageData($model, $table, $param = array(),$select_fields = '', $page = '1', $limit = '15', $order = array(),$isReturnCount = true){
if(empty($model) || empty($table)){
return false;
}
$this -> load -> model($model); $table = $this->db->dbprefix.$table;
//处理查询字段
if(!empty($select_fields)){
$this->db->select($select_fields)->from($table);
}elseif(isset($this -> $model -> selectFields)){
$this->db->select($this -> $model -> selectFields)->from($table);
}else{
$this->db->select('*')->from($table);
}
//处理查询条件
if (is_array($param) && count($param) > 0){
$this -> parseParam($param);
}
//统计总数
if($isReturnCount){
$rs['count'] = $this->db->count_all_results('',false);//不重置查询构造器
array_push($this -> errors,$this->db->last_query());
}
//分页数据处理
if(isset($page) && isset($param['limit'])){
//分页边界值 设置
$offset = $param['page'] <= 1 ? 0 : ($param['page']-1) * $param['limit'];
$this->db->limit($param['limit'], $offset);
} //排序规则的组合
if (!empty($order) && is_array($order))
{
foreach ($order as $key => $val)
{
$this->db->order_by($key, $val);
}
}else{
//默认按照此表的主键倒序
$primary = $this->getPrimary();
if(!empty($primary))
{
$this->db->order_by($primary, 'DESC');
}
}
$query = $this->db->get();
array_push($this -> errors,$this->db->last_query());
$rs['list'] = $query->result_array();
return $rs; }
/**
* 解析参数
*/
private function parseParam($param){
if(isset($param['compare'])){
foreach ($param['compare'] as $key => $val){
if (!empty($val)) $this->db->where($key, $val);
}
}
if(isset($param['like'])){
foreach ($param['like'] as $key => $val){
if (!empty($val)) $this->db->like($key, $val);
}
}
if(isset($param['in'])){
foreach ($param['in'] as $key => $val){
if (!empty($val)) $this->db->where_in($key, $val);
}
}
if(isset($param['customStr'])){
if (!empty($val)) $this->db->where($param['customStr']);
}
}
/**
* 新增信息
* @param string $table 表名称
* @param array $param 数据变量
* @return INT ID
*/
public function add($table = '', $param = array())
{
if(empty($table) || !is_array($param) || empty ($param)){
return FALSE;
} //写入数据表
$this->db->insert($table, $param);
array_push($this -> errors,$this->db->last_query());
//返回记录ID
return $this->db->insert_id();
} /**
* 更新分类信息
* @param string $table 表名称
* @param string $primary 表主键
* @param int $id 分类ID
* @param array $param 更新的数据
* @return type
*/
public function update($table = '', $primary = '', $id = 0, $param = array())
{
if(empty($table) || empty($primary) || empty($param) || empty($id))
{
return FALSE;
} $id = (int)$id;
$this->db->where($primary, $id)
->limit(1)
->update($table, $param);
array_push($this -> errors,$this->db->last_query());
return $this->db->affected_rows();
} /**
* 删除指定ID记录
* @param string $table 表名称
* @param string $primary 表主键
* @param array $id 分类ID
* @return int
*/
public function delete($table = '', $primary = '', $id = array()){
if(empty($table) || empty($primary) || empty($id)){
return FALSE;
}
$this->db->where_in($primary, $id)
->delete($table);
array_push($this -> errors,$this->db->last_query());
return $this->db->affected_rows();
} /**
* 获取表的主键
* @param string $database 数据库名称
* @param strting $table 表名称
*/
public function getPrimary($table = '', $database = self::dataBase)
{
if(empty($database) || empty($table))
{
return FALSE;
}
$sql = "SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING (constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
AND t.table_schema='qndnew'
AND t.table_name='qnd_user'";
$query = $this->db->query($sql)->result_array();
return isset($query[0]['column_name']) ? $query[0]['column_name'] : false;
}
/**
* debug sql语句
*/
public function debugSql(){
if(count($this->errors) > 0){
foreach($this->errors as $val){
echo $val.'<br>';
}
}
}
}
具体的业务逻辑模型如下:
class User_model extends My_model {
const USER = 'qnd_user';
public $selectFields = array(
'id',
'guid',
'phone',
'userName',
'password',
'headPortraits',
'nickName',
'createTime',
);
const SMS_ROLE = 'qnd_role';
public function __construct()
{
}
}
控制器中测试如下:
public function modelTest(){
$this -> load -> model('User_model'); // 載入 model
$whereArr = array(
'compare'=>array(
'userName' => 'Frank',
),
);
$rs = $this -> User_model -> pageData('User_model','user',$whereArr);
print_r($rs);
$this -> User_model -> debugSql();
}
ci公共模型类的更多相关文章
- Util应用程序框架公共操作类(一):数据类型转换公共操作类(介绍篇)
本系列文章将介绍一些对初学者有帮助的辅助类,这些辅助类本身并没有什么稀奇之处,如何能发现需要封装它们可能更加重要,所谓授之以鱼不如授之以渔,掌握封装公共操作类的技巧才是关键,我会详细说明创建这些类的动 ...
- day100:MoFang:用户模型类的创建&Marshmallow模块&使用基本构造器Schema完成数据的序列化转换和反序列化转换
目录 1.用户模型的创建 2.Marshmallow模块 3.MarshMallow基本构造器:Schema 1.基于Schema完成数据序列化转换 2.基于Schema完成数据反序列化转换 3.反序 ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- Django模型类Meta元数据详解
转自:https://my.oschina.net/liuyuantao/blog/751337 简介 使用内部的class Meta 定义模型的元数据,例如: from django.db impo ...
- Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)
今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...
- Util应用程序框架公共操作类(九):Lambda表达式扩展
上一篇对Lambda表达式公共操作类进行了一些增强,本篇使用扩展方法对Lambda表达式进行扩展. 修改Util项目的Extensions.Expression.cs文件,代码如下. using Sy ...
- Util应用程序框架公共操作类(八):Lambda表达式公共操作类(二)
前面介绍了查询的基础扩展,下面准备给大家介绍一些有用的查询封装手法,比如对日期范围查询,数值范围查询的封装等,为了支持这些功能,需要增强公共操作类. Lambda表达式公共操作类,我在前面已经简单介绍 ...
- Util应用程序框架公共操作类(七):Lambda表达式公共操作类
前一篇扩展了两个常用验证方法,本文将封装两个Lambda表达式操作,用来为下一篇的查询扩展服务. Lambda表达式是一种简洁的匿名函数语法,可以用它将方法作为委托参数传递.在Linq中,大量使用La ...
- Util应用程序框架公共操作类(六):验证扩展
前面介绍了仓储的基本操作,下面准备开始扩展查询,在扩展查询之前,首先要增加两个公共操作类,一个是经常要用到的验证方法,另一个是Lambda表达式的操作类. 很多时候,我们会判断一个对象是否为null, ...
随机推荐
- ubuntu系统内核替换
此处将内核由高版本替换成低版本.替换前的系统为ubuntu 12.04 kernel 3.8.0. 替换后的内核版本为2.6.35. 首先下载需要替换的内核文件,下载链接:https://www.ke ...
- 从底层谈WebGIS 原理设计与实现(三):WebGIS前端地图显示之根据地理范围换算出瓦片行列号的原理(转载)
从底层谈WebGIS 原理设计与实现(三):WebGIS前端地图显示之根据地理范围换算出瓦片行列号的原理 1.前言 在上一节中我们知道了屏幕上一像素等于实际中多少单位长度(米或经纬度)的换算方法, ...
- MySQL的"旁门左道"用法总结
不断更新. 一.显示当前MySQL服务的版本:1是直接在查询窗口select version();2是show variables like 'version';
- 网上搜集的一段php可逆加密函数
php加密函数: function my_encrypt($data, $key='unun.in') { $char = $str = ''; $key = md5($key); $x = 0; $ ...
- C# 程序只能执行一次
应用程序的主入口点. //每一个程序只能运行一个实例 bool isRun = false; System.Threading.Mutex m = new System.Threading.Mutex ...
- oracle存储过程返回结果集
http://www.2cto.com/database/201204/127180.html oracle实现存储过程返回查询结果集合的方法 --实现存储过程返回查询结果集合的方法 ,以下代码来 ...
- 车大棒浅谈for循环+canvas实现黑客帝国矩形阵
背景: 一日在网上闲逛的之时,突然看到一个利用JQ插件实现canvas实现的电影黑客帝国的小Demo.觉得创意不错,就下载下来研究一下. 网上浏览jQuery的写法 $(document).ready ...
- FP Tree算法原理总结
在Apriori算法原理总结中,我们对Apriori算法的原理做了总结.作为一个挖掘频繁项集的算法,Apriori算法需要多次扫描数据,I/O是很大的瓶颈.为了解决这个问题,FP Tree算法(也称F ...
- [Scoi2010]游戏
游戏 Time Limit:5000MS Memory Limit:165888KB 64bit IO Format:%lld & %llu Submit Status Pra ...
- 机器学习实战笔记(1)——k-近邻算法
机器学习实战笔记(1) 1. 写在前面 近来感觉机器学习,深度学习神马的是越来越火了,从AlphaGo到Master,所谓的人工智能越来越NB,而我又是一个热爱新潮事物的人,于是也来凑个热闹学习学习. ...