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

I have two queries, the first one gives me an array of identifiers, which is in a specific order. Then this array of identifiers passes it to the second request, for example:

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

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

+6
source share
3 answers

MySQL's sorting method with the order is the same as in where in :

 $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(); 
+9
source

You can do

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

This is a problem when MySql does not return the result in the order you specify, so after that you need to change the order.

A similar solution can be found here: do not sort by keyword MYSQL IN

+3
source

If you have a sort order of 4,2,6,9, you can get these lines and then use php to sort.

+1
source

Source: https://habr.com/ru/post/976196/


All Articles