Amarja Amarja - 1 year ago 65
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download