thinphp3.2 增删改查
<?php namespace Home\Controller; use Think\Controller; use Home\Model\BookModel; use Home\Model\ArticleModel; /** * 文章 控制器 * Class BookController * @package Home\Controller * @author centphp * @date */ class ArticleController extends Controller { /** * 文章详情 * @param int $id */ public function detail($id = 0) { //书目的相关信息 //$id = I('param.id', 0); $model = M("book"); $book_info = $model->field(true)->find($id); //阅读量加1 $bookids = cookie('$bookids') ? cookie('$bookids') : []; if (!in_array($id, $bookids)) { $model->where(['id' => $id])->setInc('clicks', 1); } array_push($bookids, $id); $bookids = array_unique($bookids); cookie('$bookids', $bookids); //文章信息 $article = M('article'); $article_info = $article->where(['bookid' => $id, 'status' => '1'])->field(true)->order(['created_at'])->select(); $this->assign('book_info', $book_info); $this->assign('article_info', $article_info); $this->display(); } /** * 删除文章 * @param int $id 文章id */ public function del($id = 0) { $model = M('article'); $data['status'] = 2; $res = $model->where(['id' => $id])->save($data); if ($res) { $json = [ 'code' => 1, 'msg' => '删除成功' ]; //$this->success('删除成功'); } else { $json = [ 'code' => 0, 'msg' => '删除失败' ]; //$this->error('删除失败'); } echo json_encode($json); exit; } /** * 编辑文章保存 * @param int $id */ public function edit($id = 0) { if (IS_POST) { $model = M('article'); $article_info = $model->find($id); $data['id'] = $id; $data['content'] = I('content', ''); //$res = $model->save($data); // 手动进行令牌验证 if (!$model->autoCheckToken($_POST)) { $json = [ 'code' => 2, 'msg' => '重复提交' ]; } else { $res = $model->save($data); if ($res) { $json = [ 'code' => 1, 'msg' => '编辑成功', 'url' => U('detail', ['id' => $article_info['bookid']]), ]; //$this->success('添加成功', 'index'); } else { $json = [ 'code' => 0, 'msg' => '编辑失败' ]; //$this->error('添加失败'); } } echo json_encode($json); exit; } else { //获取文章信息 $model = D('article'); $data = $model->relation('book')->find($id); $this->assign('data', $data); $this->display(); } } /** * 添加文章 * @param int $bookid */ public function add($bookid = 0) { if (IS_POST) { $model = M('article'); $data['bookid'] = I('bookid', ''); $data['content'] = I('content', ''); $data['created_at'] = date('Y-m-d H:i:s'); //$res = $model->add($data); // 手动进行令牌验证 if (!$model->autoCheckToken($_POST)) { $json = [ 'code' => 2, 'msg' => '重复提交' ]; } else { $res = $model->add($data); if ($res) { $json = [ 'code' => 1, 'msg' => '添加成功', 'url' => U('detail', ['id' => $bookid]), ]; //$this->success('添加成功', 'index'); } else { $json = [ 'code' => 0, 'msg' => '添加失败' ]; //$this->error('添加失败'); } } echo json_encode($json); exit; } else { //书目列表 $book_list = M('book')->field(['id', 'name'])->where(['status' => 1])->select(); $this->assign('bookid', $bookid); $this->assign('book_list', $book_list); $this->display(); } } }