サマリー:<?phpnamespace app\admin\controller;use think\Controller;use app\admin\controller\Common;use app\admin\model\NewsModel;use think\facade\Request;use think\facade\Session;class News extends Common{ &
<?php
namespace app\admin\controller;
use think\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();
//按照id降序進(jìn)行查看,分頁每頁8條數(shù)據(jù)
$new = $news->order('id','desc')->paginate(8);
$this->view->new=$new;
//渲染新聞列表
return $this->fetch();
}
public function add(){
//渲染添加界面
return $this->fetch();
}
//新聞內(nèi)容的上傳框的操作,添加圖片
public function upload(){
//獲取前臺(tái)提交的圖片信息
$file = Request::file('img');
//驗(yàn)證文件并移動(dòng)到指定目錄>>會(huì)被自動(dòng)創(chuàng)建在public中
if($info = $file->validate(['ext'=>'jpg,jpeg,png,gif'])->move('upload')){
//返回上傳成功的信息
return json(['errno'=>0,'data'=>['/upload/'.$info->getSaveName()]]);
}else{
//返回錯(cuò)誤信息
return $file->getError();
}
}
//將內(nèi)容添加到數(shù)據(jù)庫中
public function DOAdd(){
//獲取上傳信息
$data = Request::param();
//加入發(fā)布的時(shí)間
$data['time'] = time();
//加入發(fā)布新聞的管理員名稱
$data['username'] = Session::get('username');
//獨(dú)立接收新聞標(biāo)題字段,用于驗(yàn)證是否重復(fù)
$title=$data['title'];
$news=NewsModel::where('title',"$title")->find();
if($news == true){
return['res'=>0,'msg'=>'新聞標(biāo)題重復(fù)!'];
}
//如果新聞標(biāo)題不重復(fù),將內(nèi)容添加到數(shù)據(jù)表中,并且進(jìn)行存儲(chǔ)驗(yàn)證
$new = new NewsModel();
if($new->save($data)){
return['res'=>1,'msg'=>'發(fā)布成功!'];
}else{
return['res'=>0,'msg'=>'發(fā)布失??!'];
}
}
public function edit(){
//查詢新聞原有的信息
$newId = Request::param('id');
$new = NewsModel::get($newId);
//將數(shù)據(jù)賦值到模板
$this->view->new=$new;
//渲染編輯頁面
return $this->fetch();
}
public function DoEdit(){
//獲取前臺(tái)提交的數(shù)據(jù)
$data = Request::param();
$new = new NewsModel();
//$res用來接收更新操作的結(jié)果,save的第二個(gè)參數(shù)是修改條件
$res = $new->save([
'title'=>$data['title'],
'desc'=>$data['desc'],
'content'=>$data['content'],
'username'=>Session::get('username'),
'time'=>time(),
],['id'=>$data['id']]);
//驗(yàn)證修改結(jié)果
if($res){
return ['res'=>1,'msg'=>'修改成功!'];
}else{
return ['res'=>0,'msg'=>'修改失敗!'];
}
}
//刪除操作
public function del(){
//獲取需要?jiǎng)h除的新聞id
$newId = Request::param('id');
//刪除并驗(yàn)證
$new = new NewsModel();
if($new->destroy($newId)){
return['res'=>1,'msg'=>'刪除成功!'];
}else{
return['res'=>0,'msg'=>'刪除失??!'];
}
}
}
添削の先生:天蓬老師添削時(shí)間:2019-04-12 14:08:37
先生のまとめ:public function DoEdit(), 這樣的方法命名,其實(shí)是不對的, 應(yīng)該是: doEdit(), 請參考官方手冊