Do Thanh Dat
Do Thanh Dat

Reputation: 265

Query Laravel Select WhereIn Array

This query does not work correctly, it only shows 1 row

 $data = Post::select('id', 'name')
   ->whereIn('id', [$order])
   ->orderByRaw(\DB::raw("FIELD(id, $order)"))
   ->get();

but this works fine, it shows all rows

  $data = Post::select('id', 'name')
    ->whereIn('id', [1,2,3])
    ->orderByRaw(\DB::raw("FIELD(id, $order)"))
    ->get();

Thank you!

Upvotes: 21

Views: 109924

Answers (2)

Rakesh Kumar
Rakesh Kumar

Reputation: 4420

Your Query is Here:-

$data = Post::select('id', 'name')
  ->whereIn('id', $order)
  ->orderByRaw(\DB::raw("FIELD(id, ".implode(",",$order).")"))
  ->get();

Remove [] from $order.

For WhereIn condition second parameter should be an array. So the $order should be

$order = [1,2,3,4]

Upvotes: 44

D.Dimitrioglo
D.Dimitrioglo

Reputation: 3663

If your $order is an array, i think that you should do this

whereIn('id', $order) instead of whereIn('id', [$order])

P.S. In official documentation mentioned that second argument should be an array:

$users = DB::table('users')
             ->whereIn('id', [1, 2, 3])
             ->get();

Upvotes: 12

Related Questions