21

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!

0

2 Answers 2

45

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]
Sign up to request clarification or add additional context in comments.

10 Comments

This's my code $keys=array_keys($request->all()); $order=join(", ",$keys);
Use only this $order= array_values($request->all()); and (\DB::raw("FIELD(id, ".implode(",", $order).")")
use like this $order = array_values($request->all()) and \DB::raw("FIELD(id, ".implode(",", $order).")")
can u write o/t of $request->all() so we can debug.
Array ( [2] => 1 [3] => 4 [4] => 2 )
|
12

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

6 Comments

come on, see my first query :|
Here $keys=array_keys($request->all()); $order=join(", ",$keys);
Here Array ( [2] => 1 [3] => 4 [4] => 2 )
yes, i tried and had error Array to string conversion
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.