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

Elaine Marley

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?

Jarek Tkaczyk

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();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

SQLAlchemy - Get query results in same order as IN clause

From Dev

How to conditional order results in mySql?

From Dev

How does order by position clause work in mysql

From Dev

MySQL: How to use CASE for ORDER BY clause

From Dev

MySQL: How to use CASE for ORDER BY clause

From Dev

mysql dynamic ORDER BY clause

From Dev

Specific ORDER BY clause in MySQL

From Dev

MYSQL - ORDER BY clause

From Dev

mysql dynamic ORDER BY clause

From Dev

Optimizing JOINED results with Order By clause

From Dev

Why MySQL does not return rows in same order as appeared in IN clause?

From Dev

Laravel Eloquent: How to order results of related models?

From Dev

Multiple order to one receipt, select clause with no redundant results, how?

From Dev

Order by Points but if the same order by in MySQL

From Dev

How to set order clause

From Dev

How to set order clause

From Dev

How to use in clause in order by?

From Dev

Oracle "order by" clause returning results in wrong order or with results missing

From Dev

How to get query result in same order as given in clause

From Dev

Using FIELD() in ORDER BY clause - MySQL

From Dev

MySQL query / clause execution order

From Dev

Using FIELD() in ORDER BY clause - MySQL

From Dev

MySQL - Where clause processing order

From Dev

MySql Indexs for where and order by clause

From Dev

ORDER BY clause based on value - MySQL

From Dev

Sqlalchemy get results in the same order

From Dev

How to define a custom order in ORDER BY clause?

From Dev

The order by clause returns wrong results in sub query

From Dev

How to use sum, join, order by and where clause in mysql?