您的当前位置:首页>全部文章>文章详情

thinkphp使用where in查询order按照in的顺序排序

发表于:2023-02-20 22:56:22浏览:821次TAG: #ThinkPHP #where #order排序

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();
    }