新闻的增删改查操作练习代码,和管理员模块差不多。通过模版渲染,数据输入,数据获取接收,实例化模块,对数据库增加或者对应的id记录进行操作。
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/26 * Time: 10:04 */ namespace app\admin\controller; use app\admin\controller\Common; use app\admin\model\NewsModel; use think\facade\Request; use think\facade\Session; class News extends Common { public function index() { $news =new NewsModel(); //实例化新闻模型 $new = $news->order('id','desc') //查询并按照id降序 ->paginate(5); //按5条分页 $this->view->new=$new; //查询数据赋值 //渲染新闻列表 return $this->fetch(); } public function add() { //渲染新闻添加界面 return $this->fetch(); } public function upload() { //上传新闻图片方法 $file = Request::file('img'); //获取前台上传提交过来的图片信息 if($info = $file->validate(['ext'=>'jpg,jpeg,png,gif']) //判断图片后缀 ->move('upload')){ //移动目录 return json(['errno'=>0,'data'=>['/upload/'.$info->getSaveName()]]); //返回成功信息 } else { return $file->getError(); //返回错误信息 } } public function DoAdd() { //添加操作 $data = Request::param(); //获取数据 $data['time'] = time(); //获取当前时间 $data['username'] = Session::get('username'); //获取管理员名称 $title = $data['title']; //获取标题,进行判断 //创建模型 验证标题是否重复 $news = NewsModel::where('title',$title)->find(); if($news == true){ //提示信息 return ['res'=>0,'msg'=>'新闻标题重复']; } //不重复存入数据库 $new = new NewsModel(); //实例化模型 if($new->save($data)){ return ['res'=>1,'msg'=>'添加成功']; }else{ return ['res'=>0,'msg'=>'添加失败']; } } public function edit() { //接收传递过来的ID $newId = Request::param('id'); //通过ID查询数据并传给变量$new $new = NewsModel::get($newId); //将数据赋值到模版 $this->view->new=$new; //渲染编辑页面 return $this->fetch(); } //编辑更新写入 public function DoEdit() { //获取修改后提交的数据 $data = Request::param(); //实例化模型 $new = new NewsModel(); //更新操作 $res = $new->save([ 'title' => $data['title'], 'desc' => $data['desc'], 'content' => $data['content'], 'username' => Session::get('username'), 'time' => time(), ],['id'=>$data['id']]); //更新条件 //验证修改结果 if($res){ return ['res'=>1,'msg'=>'修改成功']; }else{ return ['res'=>0,'msg'=>'修改失败']; } } public function del() { //获取要删除的ID $newId = Request::param('id'); //实例模型 $new = new NewsModel(); if($new->destroy($newId)){ //返回提示信息 return ['res'=>1,'msg'=>'删除成功']; }else{ return ['res'=>0,'msg'=>'删除失败']; } } }