thinkphp使用where in查询order按照in的顺序排序
发表于:2023-02-20 22:56:22浏览:4161次
thinkphp使用各种查询语句确实很方便,但是也有个别特殊的查询,这里主要介绍一下如何保证mysql查询按in的顺序输出。
1、ThinkPHP6使用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();
2、ThinkPHP5的方式:
引入use think\db\Expression;
<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\db\Expression;
class Test extends Controller
{
public function index()
{
$ids = implode(',',[1,4,844,6,900,10]);
$exp = new Expression('field(id,'.$ids.')');
$list = Db::name('Material')
->whereIn('id',$ids)
->field('id,rank')
->order($exp)
->select();
}
}
另一种写法:
// 详情
public function detail($ids = ''){
$combination = $this->model->get($ids);
// 根据goods—ids 里面的值,按照原来的排序出来
//$combination['goods_ids'] == 1,5,4,7,1,3
$exp = new Expression("field(id,{$combination['goods_ids']})");
$goods = Goods::where("FIND_IN_SET(`id`,'{$combination['goods_ids']}')")
->field('id')
->orderRaw("field(id,{$combination["goods_ids"]})")
->select();
}
推荐文章
- Thinkphp6使用mPdf实现生成pdf文件
- 开源的Linux 服务器运维管理面板1Panel V2 版本正式发布
- OA系统设计中,用户权限一般如何划分?
- 国产开源操作系统 深度操作系统deepin 23 Preview发布
- 前端开发中项目常用的20多个轮子 快速提高开发效率 建议收藏
- 移动端微信、企业微信中使用H5的input file时只能选择手机的图片,不能选择文档文件的解决方案
- 韦伯空间望远镜飞行软件采用 C++ 编写、内置定制的JS解释器
- ThinkPHP6多条件搜索查询,表达式查询 FIND_IN_SET查询
- 微信H5版使用php Ffmpeg将微信录音amr转mp3
- 前端报错:was loaded over HTTPS, but requested an insecure错误解决方案

