PHP ThinkPHP 非常好用的增删改查方法

获取列表数据(多条)

   /**
* 获取页面列表
* @param $params //查询条件 例:['id'=>['in','1,2']] ['status'=>1]
* @param array $orderby //排序 例:['id'=>'desc']
* @param array $limit //查询页数 例:[0,10]
* @param bool $is_total 是否需要总数
* @param string $fields 是否需要总数 例:'name'
* @return array
*/
public function resultsAction($params = [],$orderby = [],$limit = [],$is_total = true,$fields = ''){
if(empty($orderby)){
$orderby = array('id'=>'desc');
}

//列表模型
$results = $this
->where($params)
->order($orderby)
->field($fields);

//查询数量
if(!empty($limit)){
list($offset, $limit) = [$limit[0],$limit[1]];

$results = $results->limit($offset,$limit);
}

//查询
$results = $results->select();

//把数据转为数组
$results = collection($results)->toArray();

//总数
if (!$is_total){
return $results;
}

//查询总数
$total = $this
->where($params)
->count();


return $result = array("total" => $total, "rows" => $results);
}

获取单条数据

   /**
* 获取单数据
* @param array $params
* @param string $fields
*/
public function resultAction($params = [],$fields = ''){
$result = $this
->field($fields)
->where($params)
->find();

if(!empty($result)){
$result=$result->toArray();
}
return $result;
}

新增或修改数据

   /**
* 新增或修改数据
* @param array $params 更新内容
* @param array $args 更新条件 存在值为更新
*/
public function saveAction($params = [],$args = []){
if(empty($args)){
$save = $this
->allowField(true)
->save($params);
}
else{
$save = $this
->allowField(true)
->update($params,$args);
}

return $save;
}

删除数据

   /**
  *删除
* @param array $params //查询条件 例:['id'=>['in','1,2']] ['status'=>1]
*/
public function delAction($params = []){
$del = $this
->where($params)
->delete();
return $del;
}

插入多条数据

   /**
* 新增
* @param array $params 更新内容
*/
public function saveAllAction($params = []){
$save = $this
->allowField(true)
->saveAll($params);

return $save;
}
posted @ 2019-11-27 18:18  幽暗天琴  阅读(539)  评论(0编辑  收藏  举报