我有一个记录ID为的数组
$record_ids = [60, 66, 70, 64, 69, 67, 65, 57];
我通过使用模型得到行,比如:
$result = Model::whereIn('id', $record_ids)->get();
问题是,我想获得与$record_ids数组中相同的行顺序。Laravel按ID升序向我返回这些行,如下所示:
[57, 60, 64, 65, 66, 67, 69, 70]
如何做到这一点?如何使Laravel"不按ID ASC默认订购"?谢谢
您可以像一样使用orderByRaw()
$result = Model::whereIn('id', $record_ids)
->orderByRaw("field(id,".implode(',',$record_ids).")")
->get();
在集合中使用sortBy方法,可以按id数组排序。
$theIds = [2,76,423];
$collection = $collection->sortby(function($model) use ($theIds){
return array_search($model->id, $theIds);
});
最好对$record_ids进行切片,这将作为偏移和限制,然后在运行查询后对返回的集合进行排序。