新闻的增删改查

原创 2018-12-25 11:03:40 289
摘要:<?php namespace app\admin\controller; use app\admin\controller\Common; use app\admin\model\NewsModel; use think\facade\Request; use think\response\Json; use think\rou
<?php
namespace app\admin\controller;

use app\admin\controller\Common;
use app\admin\model\NewsModel;
use think\facade\Request;
use think\response\Json;
use think\route\Resource;
use think\facade\Session;

class News extends Common
{
    public function index()
    {
        $news = new NewsModel();
        $new = $news->order('id','desc')->paginate(3);
        $this->view->new=$new;
        //渲染新闻列表
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function upload()
    {
        $file = Request::file('img');
        if($info = $file->validate(['ect' => 'jpg,jpge,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()
    {
        $newId = Request::param('id');
        $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()
    {
        $newId = Request::param('id');

        $new = new NewsModel();

        if($new->destroy($newId))
        {
            return ['res' => 1, 'msg' => '删除成功!'];
        }
        else{
            return ['res' => 0, 'msg' => '删除失败!'];
        }
    }

}


批改老师:韦小宝批改时间:2018-12-25 11:05:27
老师总结:不错不错!写的很棒!代码清晰有条例!继续加油吧!

发布手记

热门词条