laravel框架中根据whereIn条件指定参数的顺序排序示例代码

2023-06-01 00:00:00 示例 框架 顺序

今天我的laravel项目有个需求:根据whereIn('id',[9,12,10,6,7])这个传入的id值顺序排序

这样的功能可以使用FIND_IN_SET函数方便指定特定参数的实现


示例代码:

//查出数据特定排序 (测试数据,这里我直接写死了)

$companys = Models\CompanyCreditCard::select('id','name','nameshort','Tel','bankpy','bankcenterpy','logo')
            ->whereIn('id',[9,12,10,6,7])
                //按照whereIn条件指定顺序排序
            ->orderByRaw(DB::raw("FIND_IN_SET(id, '" . implode(',', [9,12,10,6,7]) . "'" . ')'))
            ->get();


dd() 效果:看id列

array:1 [▼
  "companys" => array:5 [▼
    0 => array:13 [▼
      "id" => 9
      "name" => "平安银行"
      "nameshort" => "平安"
      "Tel" => "40088-24-365"
      "bankpy" => "pingan"
      "bankcenterpy" => "pinganbank"
      "logo" => "companys/9.png"
    ]
    1 => array:13 [▼
      "id" => 12
      "name" => "兴业银行"
      "nameshort" => "兴业"
      "Tel" => "95561"
      "bankpy" => "xingye"
      "bankcenterpy" => "xybank"
      "logo" => "companys/12.png"
    ]
    2 => array:13 [▼
      "id" => 10
      "name" => "中信银行"
      "nameshort" => "中信"
      "Tel" => "400-88-95558"
      "bankpy" => "zhongxin"
      "bankcenterpy" => "zxbank"
      "logo" => "companys/10.png"
    ]
    3 => array:13 [▼
      "id" => 6
      "name" => "交通银行"
      "nameshort" => "交行"
      "Tel" => "400-800-9888"
      "bankpy" => "jiaohang"
      "bankcenterpy" => "bankcomm"
      "logo" => "companys/6.png"
    ]
    4 => array:13 [▼
      "id" => 7
      "name" => "浦发银行"
      "nameshort" => "浦发"
      "Tel" => "800-820-8788"
      "bankpy" => "pufa"
      "bankcenterpy" => "spdb"
      "logo" => "companys/7.png"
    ]
  ]


相关文章