tp5增删、改查

//规范写法

private $obj;
public function _initialize()
{
$this->obj = model('Category');
}

public function index()
{
$parentId = input('get.parent_id',0,'intval');
$categorys = $this->obj->getFirstCategory($parentId); //获取一级分类
return $this->fetch('',[
'categorys'=>$categorys
]);
}

input获取的是form表单的name值或者get方式传的参数

然后插入到页面中

public function getFirstCategory($parentId = 0){
$data = [
'status' => ['neq',-1],
'parent_id' => $parentId
];
$order = [
'id' => 'desc'
];
$result = $this->where($data)->order($order)->paginate(2);
return $result;

增删改都是save() 查是select()

删只不过是把status变为-1

public function save()
{
//print_r($_POST);
//print_r(request()->post());


//做严格判断
if(!request()->isPost()){
$this->error('请求失败');
}
//校验
$data = input('post.');
$validate = validate('Category'); //生成一个Validate类对象
if(!$validate->scene('add')->check($data)){
$this->error($validate->getError());
}

if(!empty($data['id'])){
return $this->update($data);
}

//把数据$data提交到model层
$res = $this->obj->add($data); //生成一个model层对象,model是公共的
if($res){
$this->success('插入成功');
}else{
$this->error('插入失败');
}
}
//编辑页面
public function edit($id=0){
// echo input('get.id');
if(intval($id) < 1){
$this->error('参数不合法');
}
$categorynow = $this->obj->get($id); //全部都打出来
$category = $this->obj->getNormalFirstCategory();
return $this->fetch('',[
'category'=>$category,
'categorynow'=>$categorynow
]);
}


public function update($data){
$res = $this->obj->save($data,['id' => intval($data['id'])]); //关联数组
if($res){
$this->success('修改成功');
}else{
$this->error('修改失败');
}
}


//修改状态
public function status(){
$data = input('get.');
$validate = validate('Category'); //生成一个Validate类对象
if(!$validate->scene('status')->check($data)){
$this->error($validate->getError());
}
$res = $this->obj->save(['status'=>$data['status']],['id' => $data['id']]); //关联数组
if($res){
$this->success('状态更新成功');
}else{
$this->error('状态更新失败');
}
}
}

仅供参考,具体情况具体分析

原文地址:https://www.cnblogs.com/liangdong/p/10520859.html