laravel 模型查询按照whereIn排序

$ids = [5,7,3,1,2];
$data = Content::whereIn('id',$ids)
->select('id')
->get();
//查询结果是想按照wherein的顺序排序
//正确写法
$data = Content::whereIn('id',$ids)
->select('id')
// ->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $ids) . '"' . ")"))
// ->orderBy(DB::raw("FIND_IN_SET(id, '" . implode(',', $ids) . "'" . ')'))
// ->orderByRaw("FIND_IN_SET(id, '" . implode(',', $ids) . "'" . ')')
->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $ids) . '"' . ")"))
->get();

执行的sql

select `id`, `name`, `wx_avatar` from `wm_user` where (`is_delete` = "0") and `id` in ("1643", "100001", "7036") order by FIND_IN_SET(id, '1643,100001,7036')

原文地址:https://www.cnblogs.com/webclz/p/10967724.html