项目中需要用到很多模型的操作方法,这里自己结合经验整理了一些我认为常用的方法。
以下实例用 USER 表 作为数据表,进行演示。/**
* 列表 加分页
* @param string $field
* @param array $where
* @param int $page
* @param int $pagesize
* @param string $order
* @return array
*/
public function getUserList($field = '', $where = array(),$page=1,$pagesize=20, $order = ''){
$data = $this->field($field)->where($where)->page($page,$pagesize)->order($order)->select();
$count = $this->field($field)->where($where)->count('id');
$Page = new \Think\Page($count,$pagesize);
$show = $Page->show();
$info = array(
'data' =>$data,
'show' =>$show,
);
return $info;
}
/**
* 列表 不分页
* @param string $field
* @param array $where
* @param string $order
* @return mixed
*/
public function getUserLists($field = '',$where = array(), $order = ''){
$info = $this->field($field)->where($where)->order($order)->select();
return $info;
}
/**
* 获取单个记录详细信息
* @param string $field
* @param array $where
* @return mixed
*/
public function getUserInfo($field='',$where=array()){
$info = $this->field($field)->where($where)->find();
return $info;
}
/**
* 添加与修改记录
* @param array $where
* @param array $data
* @return mixed
*/
public function addUser($where=array(),$data=array()){
if($where){
$info = $this->where($where)->save($data);
}else{
$info = $this->add($data);
}
return $info;
}
/**
* 删除记录
* @param array $where
* @return mixed
*/
public function delUser($where=array()){
$info = $this->where($where)->delete();
return $info;
}
/**
* 记录字段加减
* @param $field
* @param $where
* @param int $num
* @param bool $type
* @return mixed
*/
public function setUserNum($field='',$where=array(),$num=1,$type=false){
if($type){
$info = $this->where($where)->setDec($field,$num);
}else{
$info = $this->where($where)->setInc($field,$num);
}
return $info;
}
/**
* 记录字段求和
* @param $field
* @return mixed
*/
public function getUserSum($field=''){
$info = $this->sum($field);
return $info;
}
/**
* 记录总数
* @param string $field
* @return mixed
*/
public function getUserCount($field='id',$where=array()){
$info = $this->where($where)->count($field);
return $info;
}
以上的方法,基本上满足日常的使用了。