thinkphp使用where in查询order按照in的顺序排序
发表于:2023-02-20 22:56:22浏览:2443次
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();
}
推荐文章
- 国民APP微信内测新功能:朋友圈内容可转发给好友
- Thinkphp6在Windows下使用Phpstudy工具升级或全局安装composer
- ref, toRef, toRefs,reactive, defineComponent, computed, unref, toRaw, watchEffect, onUpdated 10个VUE3前端API总结
- PHP中如何将数组转换为JSON格式数据
- 小程序进入页面时图片拉伸变形优化方案
- 开源免费的企业办公系统,勾股OA2.0发布
- linux服务器定时任务crontab命令用法详解
- Layui的table模块导出所有数据,无需修改代码,完美解决方案
- Layui 2.8.0 正式发布,她朴实归来了
- ERP、进销存、仓储管理系统到底有什么不同?