Laravel MySQL how to order results in the same order as in whereIn clause

一世执手 提交于 2019-12-05 23:07:24

问题


I have two queries, the first one gives me an array of ids, that is in a specific order. Then that array of ids I pass it to the second query like so:

 Operation::whereIn('id', $ids)->get();

But when I output the result of that query, the order has changed, if the array $ids was something like (4,2,6,9) which is the order I wanted the results to be in, the output will give me 2,4,6,9. How can I avoid that?


回答1:


MySQL way of sorting with order same as in where in clause:

$ids; // array of ids
$placeholders = implode(',',array_fill(0, count($ids), '?')); // string for the query

Operation::whereIn('id', $ids)
   ->orderByRaw("field(id,{$placeholders})", $ids)->get();



回答2:


You can do

$idsImploded = implode(',',$ids);
Operation::whereIn('id', $ids)->orderByRaw("FIND_IN_SET('id','$idsImploded')")->get();

It's a problem where MySql doesn't return the result in the order you specify them, so you need to reorder them after that.

A similar solution can be found here: avoid Sorting by the MYSQL IN Keyword




回答3:


If you have the sorting order in 4,2,6,9, you can fetch these rows, then use php to sort.



来源:https://stackoverflow.com/questions/26176245/laravel-mysql-how-to-order-results-in-the-same-order-as-in-wherein-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!