如何根据id数组获取表记录?

时间:2016-06-02 11:22:07

标签: php mysql arrays laravel

我在laravel做项目。我想根据包含列ID的数组显示所有记录。

我有数组,

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

我希望从提供者表中获取所有记录,其中id为11,15,3,7,...连续。

当我这样做的时候,

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

然后返回的数据为2,3,4,...按asc顺序。我想要11,15,3中的数据,...仅订购。

2 个答案:

答案 0 :(得分:1)

您可以使用order by field功能:

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

仅在mysql上测试

答案 1 :(得分:0)

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