其他子model类可继承此类,例如:class Admin_mdl extends MY_Model
此继承类需放在application/core下
子类继承,即可使用父类中方法
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin_mdl extends MY_Model {
const TBL_DB = 'admin_info';
public function __construct()
{
parent::__construct(self::TBL_DB);
}
}
MY_Model.php文件内容如下:
/**
* MY_Model Class ,create by luguoli
*/
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Model extends CI_Model {
var $TableName = '';
public function __construct($TableName = '')
{
parent::__construct();
$this->TableName = $TableName;
log_message('debug', $this->TableName." Model Class Initialized");
}
public function get_data_by_id($id, $type='id')
{
$data = array();
$this->db->select('*')->from($this->TableName)->where($type, $id)->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1)
{
$data = $query->row_array();
}
$query->free_result();
return $data;
}
public function get_datas($limit=NULL, $offset=NULL, $sort=NULL, $select=NULL, $where=NULL)
{
//limit
if($limit && is_numeric($limit))
{
$this->db->limit(intval($limit));
}
//offset
if($offset && is_numeric($offset))
{
$this->db->offset(intval($offset));
}
//sort,可多个字段排序,写法:id asc,openid desc
if($sort && !empty($sort))
{
$this->db->order_by($sort);
}
else
{
$this->db->order_by("id","desc");
}
//where,条件,写法:$where = array('name =' => $name, 'id <' => $id);
if($where && !empty($where))
{
$this->db->where($where);
}
//select,查询字段,写法:$select = "id,nickname,date";
if($select && !empty($select))
{
$this->db->select($select);
}
return $this->db->get($this->TableName);
}
public function get_datas_count($where=NULL)
{
$data = array();
if($where && !empty($where))
{
$this->db->where($where);
}
$this->db->select('count(*) as count')->from($this->TableName);
$query = $this->db->get();
if($query->num_rows() == 1)
{
$data = $query->row_array();
}
$query->free_result();
return $data;
}
public function remove_data($id, $type='id')
{
$this->db->delete($this->TableName, array($type => $id));
return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
}
public function add_data($data)
{
$this->db->insert($this->TableName, $data);
return ($this->db->affected_rows() > 0) ? $this->db->insert_id() : FALSE;
}
public function update_data($id, $data, $type='id')
{
$this->db->where($type, $id);
$this->db->update($this->TableName, $data);
return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
}
}
/* End of file MY_Model.php */