上移,下移 ,置顶,至尾,批量删除更新排序....

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36447759/article/details/81988889

声明:所有文章仅仅是个人笔记,不用做教程,只适合自己用(因为我怕不符合大众,容易引起误导)

原理部分:

前提:在数据库设置一个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('未选中任何数据');

       }
    }

效果图:

删除前

批量删除  

删除后

猜你喜欢

转载自blog.csdn.net/qq_36447759/article/details/81988889