Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get elements by id array and order by this array

I want te get, for example, products by id array but I want these products on same order that id array.

For example, I want products with id 6, 3, 8:

ids = [6, 3, 8]
Product.where(id: ids)

It gives me products but the first is product with id = 3, second with id = 6...

And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...

How could I do that in Products query?

like image 655
fcastillo Avatar asked Dec 07 '25 08:12

fcastillo


1 Answers

Indexing should work:

Product.where(id: ids).index_by(&:id).values_at(*ids)

Or just (checked in MySQL, but sanitize ids before if ids are coming from external source):

Product.where(id: ids).order("field(id, #{ids.join(', ')})")
like image 182
Ilya Avatar answered Dec 10 '25 01:12

Ilya