上移,下移 ,置頂,至尾,批量刪除更新排序....
阿新 • • 發佈:2018-11-12
宣告:所有文章僅僅是個人筆記,不用做教程,只適合自己用(因為我怕不符合大眾,容易引起誤導)
原理部分:
前提:在資料庫設定一個sort,根據資料庫資料的條數自增,不可重複。
上移:從前臺獲取排序欄位(我把它定為sort);根據sort,找到要交換的資料的id備用;然後sort+1,找到相鄰的上一條資料,取得他的id;然後進行更新操作,吧要交換的資料的sort變成剛剛查出來的上一條資料的sort也就是前面的(sort+1),然後把上一條資料的sort,變成從前臺獲取的sort;
下移 :與上移思路相反
置頂:和sort==1的資料進行交換sort;
至尾:計算出資料表總共有多少條資料,這個總數結束最後一條資料的sort,然後進行交換。
刪除:吧所有大於sort的資料獲取出來,然後進行遍歷,一一給他們sort減一
批量刪除更新排序:吧傳過來的資料變成一個數組,重複刪除即可。
程式碼:讓sort自動增長
public function ComnewsAdd(){ if(request()->isPost()){ $data=input('post.'); $data['time']=strtotime(date('Y:m:d H:s:m')); //新增排序(重要部分) $count=db('comnews')->count(); if($count){ $data['sort']=$count+1; }else{ $data['sort']=1; } $res=db('comnews')->insert($data); if($res){ $this->success('新增新聞成功','ComnewsLis'); }else{ $this->error('新增新聞失敗'); } } return view('News/ComnewsAdd'); }
只貼一個上移操作:
//向上移動 public function upsort(){ $data=input('post.'); $sort=$data['pai'];//要修改的sort $mydate=db('comnews')->where('sort','=',$sort)->find(); $id=$mydate['id']; //上一條資料 $topone=$sort+1; $toponeres=db('comnews')->where('sort','=',$topone)->find(); if($toponeres){ //取出上一條資料的id和sort $toponeid=$toponeres['id']; $toponesort=$toponeres['sort']; //進行更新 db('comnews')->where('id',$id)->setField('sort',$toponesort); db('comnews')->where('id',$toponeid)->setField('sort',$sort); }else{ echo "<script>alert('已經在最頂上');</script>"; } $this->redirect('/zxhl/public/admin/comnews/comnewslis.html'); }
批量刪除:
public function del_all(){
$data=input('post.');
if($data!='null'){
$ids=implode(',',$data['checkbox']);//對id進行接收
$ids=explode(",",$ids);//放入陣列中進行方便遍歷
for($i=0;$i<count($ids);$i++){
//自身的sort
$thesort=db('comnews')->field('sort')->where('id',$ids[$i])->find();
$sortres=db('comnews')->field('id,sort')->where('sort','>',$thesort['sort'])->select();
foreach($sortres as $key=>$value){
//減一
db('comnews')->where('id',$value['id'])->setField('sort',$value['sort']-1);
}
}
if(db('comnews')->delete($ids)){
$this->success('刪除新聞成功','ComnewsLis');
}else{
$this->error('刪除新聞失敗');
}
}else{
$this->error('未選中任何資料');
}
}
效果圖:
刪除前
批量刪除
刪除後