简体   繁体   English

如何防止 whereRaw 自动对我的收藏进行排序?

[英]How to prevent whereRaw from automatically sort my collection?

I have a list of ids which are id of a collection after sorted, eg:我有一个 id 列表,它们是排序后的集合的 id,例如:

$orderedIds = "2,18,4,1,17,5,6,16,15,14,13,11,12,10,9,8,7,3"

and I want to pick them out with whereRaw like this:我想像这样用whereRaw来挑选它们:

$result = Collection::whereRaw("FIELD(id, ".$orderedIds." )");

but the result is automatically sorted by id, which means the collection output is literally the original collection:但结果会自动按 id 排序,这意味着集合 output 从字面上看就是原始集合:

[
 {
   "id": 1,
   ...
 }, {
   "id": 2,
   ...
 }, {
   "id": 3,
   ...
 }
]

Any option with whereRaw , or any other way around for me to achieve the sorted collection? whereRaw的任何选项,或任何其他方式让我实现排序集合?

Try this尝试这个

 Collection::whereIn('id',$orderedId)->orderByRaw(DB::raw("FIELD(id, $orderedId)"))->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM