今天就跟大家聊聊有關(guān)laravel 模型查詢按照whereIn排序,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
實例如下所示:
$ids = [5,7,3,1,2]; $data = Content::whereIn('id',$ids) ->select('id') ->get(); //查詢結(jié)果是想按照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();
錯誤寫法
//錯誤寫法 $data = Content::whereIn('id',$ids) ->select('id') ->orderByRaw("FIND_IN_SET('id', "' . implode(",", $ids) . '"' . ")") ->get(); //該寫法查詢順序是按照id大小正序排序
原因解析
//正確寫法的sql語句為 select `id` from `contents` order by FIND_IN_SET(id, "5,6,7,4,2,1") asc //錯誤寫法的sql語句為 select `id` from `contents` order by 'FIND_IN_SET(id, "5,6,7,4,2,1")' asc //或者 select `id` from `contents` order by `FIND_IN_SET(id, "5,6,7,4,2,1")` asc //FIND_IN_SET()方法外面不要添加任何符號
看完上述內(nèi)容,你們對laravel 模型查詢按照whereIn排序有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。