order
order
方法用于对操作的结果排序或者优先级限制。用法如下:
Db::name('Admin')
->where('status', 1)
->order('id', 'desc')
->limit(5)
->select();
相当于
SELECT * FROM `admin` WHERE `status` = 1 ORDER BY `id` desc LIMIT 5
如果没有指定desc
或者asc
排序规则的话,默认为asc
。支持使用数组对多个字段的排序,例如:
Db::name('Admin')
->where('status', 1)
->order(['time'=>'desc','id'=>'desc'])
->limit(5)
->select();
最终的查询SQL可能是
SELECT * FROM `admin` WHERE `status` = 1 ORDER BY `order` desc,`id` desc LIMIT 5
对于更新数据或者删除数据的时候可以用于优先级限制
Db::name('Admin')
->where('status', 1)
->order('id', 'desc')
->limit(5)
->delete();
生成的SQL
DELETE FROM `admin` WHERE `status` = 1 ORDER BY `id` desc LIMIT 5
如果需要在order
方法中使用mysql函数的话,必须使用下面的方式:
Db::name('Admin')
->where('status', 1)
->orderRaw("field(name,'勾股OA','勾股Blog','勾股CMS')")
->limit(5)
->select();
随机查询的方法如下:
Db::name('Admin')->orderRaw("RAND()")->limit(10)->select();
使用in查询保证顺序:
orderRaw(field(id,’3,4,2,1,6,13’)),举例子:
$ids = '1,5,9,6,8,3,2';
$exp = ("field(id,".$ids.")");
$list = Db::name('Material')->where([['id','in',$ids]])->orderRaw($exp)->select();
order使用条件排序:
$where[] = ['a.delete_time', '=', 0];
$rows = $param['limit'];
$list = Db::name('Project')
->field(array('a.*','d.name as director_name','c.name as customer_name','CASE
WHEN a.status = 100 THEN 1
ELSE 2 END AS flag'))
->alias('a')
->join('Admin d', 'd.id = a.director_uid', 'LEFT')
->join('Customer c', 'c.id = a.customer_id', 'LEFT')
->where($where)
->order('flag desc,a.priority desc,a.id desc')
->paginate($rows, false, ['query' => $param]);