分类模块总结

原创 2018-12-24 19:40:06 293
摘要:一.渲染列表页面    总体来说就是查询数据分页处理,然后进行模板赋值,渲染模板    模型文件<?php namespace app\admin\model; use think\Model; use think\model\concern\SoftDelete; class

一.渲染列表页面

    总体来说就是查询数据分页处理,然后进行模板赋值,渲染模板

    模型文件

<?php

namespace app\admin\model;

use think\Model;
use think\model\concern\SoftDelete;

class Sort extends Model

{
    //使用trait软删除
    use SoftDelete;

    //表名
    protected $table = 'sort';

    //主键
    protected $pk = 'id';

    //开启自动时间戳
    protected $autoWriteTimestamp = true;


    //设置一下用户自定义的新增和更新时间的字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    //设置软删除字段
    protected $defaultSoftDelete = 'delete_time';

}

    控制器文件

namespace app\admin\controller;
use app\admin\common\Common;
use think\facade\Request;
use app\admin\model\Sort as SortModel;
use think\facade\Session;

class Sort extends Common
{
    public function index()
    {
        //获取数据
        $sorts = SortModel::order('id')->paginate(5);
        //获取分页数据
        $page = $sorts->render();

        //模板赋值
        $this->view->assign('sorts',$sorts);
        $this->view->assign('page',$page);
        //渲染列表页
        return $this->view->fetch();
    }

22.png

二.新增操作

    本页面的新增操作是在列表页中直接添加,所以不需要渲染模板页面了,直接将表单数据传到控制器中

public function doAdd()
{
    //获取提交的数据
    $data = Request::param();
    if(!$data){
        return ['res'=>0, 'msg'=>'无数据!'];
    }
    //uid传入
    $data['uid'] = Session::get('id');
    //执行添加
    $res = SortModel::create($data);
    if($res){
        return ['res'=>1, 'msg'=>'添加成功!'];
    }else{
        return ['res'=>2, 'msg'=>'添加失败!'];
    }

}

三.更新操作

    更新操作需要将id传过去,然后根据id查询出原数据,显示在视图中,然后在将更新的数据传回控制器中,进行更新

public function edit()
{
    //获取分类id
    $id = Request::param('id');
    //查询数据
    $res = SortModel::get($id);

    $this->view->assign('res',$res);
    //渲染添加页面
    return $this->view->fetch();
}
public function doEdit()
{
    //获取提交数据
    $data = Request::param();
    //判断是否为空
    if($data['id']==''){
        return ['res'=>0, 'msg'=>'非法操作'];
    }
    //session中的id传入uid
    $data['uid'] = Session::get('id');

    //执行修改
    $res = SortModel::update($data,['id'=>$data['id']]);

    //验证修改是否成功并返回对应信息
    if($res){
        return ['res'=>1, 'msg'=>'修改成功'];
    }else{
        return ['res'=>2, 'msg'=>'修改失败'];
    }
}

23.png

四.删除数据

    依旧软删除,不许无条件删除

public function del()
{
    //获取id
    $id = Request::param('id');
    //不许无di删除
    if($id==''){
        return ['res'=>0, 'msg'=>'非法操作'];
    }
    //执行删除
    $res = SortModel::destroy($id);
    if($res){
        return ['res'=>1, 'msg'=>'删除成功'];
    }else{
        return ['res'=>2, 'msg'=>'删除失败'];
    }

}

24.png

批改老师:韦小宝批改时间:2018-12-25 09:13:17
老师总结:写的很不错!这个项目写完可以考虑写个自己的博客!

发布手记

热门词条