Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 464
Do Thanh Dat Avatar asked Jul 02 '16 11:07

Do Thanh Dat


People also ask

What does whereIn do in laravel?

whereIn() Laravel Query with Example: whereIn() is used to check whether column contains value from the array or list. Basically, it is used to match column against list of values.

What is the difference between where and whereIn in laravel?

Note: where will compare with just first value of array or just one single value. and whereIn will compare evey index of array.

What is pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

What is the difference between query builder and eloquent?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.


2 Answers

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]
like image 140
Rakesh Kumar Avatar answered Oct 22 '22 00:10

Rakesh Kumar


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();
like image 30
D.Dimitrioglo Avatar answered Oct 22 '22 01:10

D.Dimitrioglo