thinkphp3、thinkphp5框架中,如何用order()实现自定义排序呢?非常有用!

thinkphp3、thinkphp5框架中,如何用order()实现自定义排序呢?

sql: select * from table where id IN (3,6,9,1,2,5,8,7) order by field(id,3,6,9,1,2,5,8,7); mysql原生语句是这样实现! 
在thinkphp3、thinkphp5框架中,如何用order()实现自定义排序呢?下面一起来看看吧!

其实非常简单原理非常简单,如下:

->order("field(id,3,6,9,1,2,5,8,7)")
如果使用模型查询的话就是:表名::where("id","in","3,6,9,1,2,5,8,7")->order("field(id,3,6,9,1,2,5,8,7)")->select();

最终代码示例:

//把结尾的逗号,去掉
            $ids = explode(',',$ids);
            $idsArr = [];
            foreach ($ids as $ckey => $cvalue) {
                if(!ctype_space($cvalue) && !empty($cvalue)){
                    $idsArr[] =trim($cvalue);
                }
            }
            $its= implode(',',$idsArr);

$items = $this->iTable
            ->alias('i')
            ->join('sss AS s ON s.id = i.id')
            ->where($where)
            ->order("field(i.id,".$its.")")

           getField('i.id');

 

你可能感兴趣的:(❤,PHP,❤,数据库)