0

I have an array like this

$products = [350, 410, 362, 256, 193]

I have used this array to get results like this:

$searchResults = ProductSearch::whereIn('product_id', $products)->get();

In this result, I am not getting product with id 350 on first element in the result collection. Is there any way to achieve such result using ORM ?

Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84

2 Answers2

0

Unless you specify ORDER BY in an sql query, the order is undefined.

To define an order from your array, use orderByRaw()

$products = [350, 410, 362, 256, 193]
 
$products_ordered = implode(',', $products);
 
$items = ProductSearch::whereIn('product_id', $products)
 ->orderByRaw("FIELD(product_id, $products_ordered)")
 ->get();

The order issue is not a Laravel issue, but an SQL issue. Read this question, where someone is having the same issue without Laravel. And these almost identical questions:

mcky
  • 823
  • 2
  • 7
  • 20
0

Have you checked that your table has a column( product_id ) available?