Laravel MySQL如何以与whereIn子句相同的顺序排序结果

时间:2014-10-03 09:09:43

标签: mysql laravel-4 eloquent

我有两个查询,第一个给我一个id数组,按特定顺序排列。然后我将这个ID数组传递给第二个查询,如下所示:

 Operation::whereIn('id', $ids)->get();

但是当我输出该查询的结果时,顺序已经改变,如果数组$ ids类似于(4,2,6,9),这是我想要结果的顺序,输出将是给我2,4,6,9。我怎么能避免这种情况?

3 个答案:

答案 0 :(得分:14)

MySQL 排序方式,其顺序与where in子句相同:

$ids; // array of ids
$placeholders = implode(',',array_fill(0, count($ids), '?')); // string for the query

Operation::whereIn('id', $ids)
   ->orderByRaw("field(id,{$placeholders})", $ids)->get();

答案 1 :(得分:4)

你可以做到

$idsImploded = implode(',',$ids);
Operation::whereIn('id', $ids)->orderByRaw("FIND_IN_SET('id','$idsImploded')")->get();

这是一个问题,MySql没有按照你指定的顺序返回结果,所以你需要在那之后对它们重新排序。

可在此处找到类似的解决方案:avoid Sorting by the MYSQL IN Keyword

答案 2 :(得分:1)

如果您在4,2,6,9中有排序顺序,则可以获取这些行,然后使用php进行排序。