Laravel在查询时失去顺序 [英] Laravel loses order when querying
本文介绍了Laravel在查询时失去顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组ID,如下所示:
array:2 [
0 => "102"
1 => "101"
]
请注意,订单很重要.
当我查询模型时:
$models = Post::whereIn('id', $keys)->get();
它会丢失订单.
因此,我希望ID为102的帖子排在101之前,但101排在第一.
如何强制查询构建器保持顺序
解决方案
您可以执行以下操作:
$ids_ordered = implode(',', $keys);
$models = Post::whereIn('id', $keys)
->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
->get();
参考 FIELD() >
I have a collection of ids as follows:
array:2 [
0 => "102"
1 => "101"
]
Please notice that order matters.
When I query the model like:
$models = Post::whereIn('id', $keys)->get();
it loses the order.
So I expect that post with id 102 comes before 101 but 101 comes first.
How can I force query builder to keep the order
解决方案
You can do something like this:
$ids_ordered = implode(',', $keys);
$models = Post::whereIn('id', $keys)
->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
->get();
Reference FIELD()
这篇关于Laravel在查询时失去顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文