Laravel:按位置排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26704575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:22:06  来源:igfitidea点击:

Laravel: order by where in

phpmysqllaravelsphinx

提问by MPikkle

I am using SphinxSearch to query some contents and have the ids of my objects that I want to query with MySQL. The array of my ids are sorted depending on their rank Sphinx gives. Thus, I would like to make a MySQL like so:

我正在使用 SphinxSearch 来查询一些内容,并拥有我想用 MySQL 查询的对象的 ID。我的 id 数组根据 Sphinx 给出的等级进行排序。因此,我想像这样制作一个 MySQL:

SELECT * FROM table WHERE id IN (1,17,2) 
ORDER BY FIELD(id,1,17,2)

I know I can do:

我知道我可以做到:

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

But I can't get the order I had.

但我无法得到我的订单。

How can I do that in a proper way with Laravel ?

我怎样才能用 Laravel 以正确的方式做到这一点?

回答by MPikkle

Solution:

解决方案:

$ids = array(1,17,2);

$ids_ordered = implode(',', $ids);

$items = static::whereIn('id', $ids)
 ->orderByRaw("FIELD(id, $ids_ordered)")
 ->get();

Additional Notes:

补充说明:

Using the solution found on an article titled Get all items at once ordered by the current order of ids in the WHERE IN clause using Eloquent:

使用标题为Get all items at once order by the current order of ids in the WHERE IN 子句使用 Eloquent的文章中找到的解决方案:

Useful when you want to orderBy the items from the database using the order of id's in the array you supplied in the WHERE IN clause. Can be easily modified to suit your needs, like provide a different order of ids to be used.

当您想使用您在 WHERE IN 子句中提供的数组中的 id 顺序对数据库中的项目进行排序时很有用。可以轻松修改以满足您的需求,例如提供要使用的不同顺序的 id。

// Raw SQL:
// SELECT * FROM items WHERE id IN (1,2,3,4,5) ORDER BY FIELD(id,1,2,3,4,5);

$itemIds = array(1,2,3,4,5);

$ids = implode(',', $itemIds);

$items = static::whereIn('id', $itemIds)
    ->orderByRaw(DB::raw("FIELD(id, $ids)"))
    ->take($limit)
    ->get();

回答by Mehdi hosein pour

I got this problem too, but my target array elements were strings. in this case ...

我也遇到了这个问题,但我的目标数组元素是字符串。在这种情况下 ...

$strings = array('xxx','yyy','zzz');

$imploded_strings = implode("','", $strings);

$items = static::whereIn('some_column', $strings)
->orderByRaw(DB::raw("FIELD(some_column, '$imploded_strings')"))
->get();