abstrakt:<?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降序進行查看,分頁每頁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(){
//獲取前臺提交的圖片信息
$file = Request::file('img');
//驗證文件并移動到指定目錄>>會被自動創(chuàng)建在public中
if($info = $file->validate(['ext'=>'jpg,jpeg,png,gif'])->move('upload')){
//返回上傳成功的信息
return json(['errno'=>0,'data'=>['/upload/'.$info->getSaveName()]]);
}else{
//返回錯誤信息
return $file->getError();
}
}
//將內(nèi)容添加到數(shù)據(jù)庫中
public function DOAdd(){
//獲取上傳信息
$data = Request::param();
//加入發(fā)布的時間
$data['time'] = time();
//加入發(fā)布新聞的管理員名稱
$data['username'] = Session::get('username');
//獨立接收新聞標題字段,用于驗證是否重復
$title=$data['title'];
$news=NewsModel::where('title',"$title")->find();
if($news == true){
return['res'=>0,'msg'=>'新聞標題重復!'];
}
//如果新聞標題不重復,將內(nèi)容添加到數(shù)據(jù)表中,并且進行存儲驗證
$new = new NewsModel();
if($new->save($data)){
return['res'=>1,'msg'=>'發(fā)布成功!'];
}else{
return['res'=>0,'msg'=>'發(fā)布失?。?#39;];
}
}
public function edit(){
//查詢新聞原有的信息
$newId = Request::param('id');
$new = NewsModel::get($newId);
//將數(shù)據(jù)賦值到模板
$this->view->new=$new;
//渲染編輯頁面
return $this->fetch();
}
public function DoEdit(){
//獲取前臺提交的數(shù)據(jù)
$data = Request::param();
$new = new NewsModel();
//$res用來接收更新操作的結果,save的第二個參數(shù)是修改條件
$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'=>'修改失?。?#39;];
}
}
//刪除操作
public function del(){
//獲取需要刪除的新聞id
$newId = Request::param('id');
//刪除并驗證
$new = new NewsModel();
if($new->destroy($newId)){
return['res'=>1,'msg'=>'刪除成功!'];
}else{
return['res'=>0,'msg'=>'刪除失??!'];
}
}
}
Korrigierender Lehrer:天蓬老師Korrekturzeit:2019-04-12 14:08:37
Zusammenfassung des Lehrers:public function DoEdit(), 這樣的方法命名,其實是不對的, 應該是: doEdit(), 請參考官方手冊