Amarja Amarja - 4 months ago 6x
SQL Question

How to fetch table records according to array of ids?

I am doing project in laravel. I want to display all records according to the array containing ids of column.

I have array as,

$prov_Data = ["11","15","3","7","8","2","4"];

and I want to fetch all records from provider table whose ids are 11,15,3,7,... serially.

For that when I did as,

$providerData = Provider::whereIn('id',$prov_Data)->get();

then returned data is as 2,3,4,... i.e. in asc order. I want data in 11,15,3,... order only.


You can use the order by field feature :

$prov_Data  =  ["11","15","3","7","8","2","4"];
$ids = implode(',', $prov_Data);
$providers = Provider::whereIn('id', $prov_Data)->orderByRaw("FIELD (id, $ids) ASC")->get();

Tested only on mysql