【问题标题】:Laravel: order by where inLaravel:按位置排序
【发布时间】:2014-12-29 12:55:40
【问题描述】:

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

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

我知道我能做到:

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

但我无法得到我的订单。

如何使用 Laravel 以适当的方式做到这一点?

【问题讨论】:

  • 查看orderByRaw

标签: php mysql laravel sphinx


【解决方案1】:

解决方案:

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

补充说明:

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

当您想使用您在 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();

【讨论】:

  • 这是纯金
  • $ids_ordered = implode(',', $itemIds); to $ids_ordered = implode(',', $ids);
  • 这仅适用于 mysql。我不得不使用 php 来排序,因为我使用 postgres
  • 如原帖所述,这是一个专门针对 MySQL 的问题。您可以尝试使用以下方式更改原始 SQL:stackoverflow.com/questions/866465/order-by-the-in-value-list
  • 这太不可思议了!
【解决方案2】:

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

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

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

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

【讨论】:

  • 对我有用的是:$searchedStrings = "'".implode("', '", $originalArrayOfStrings)."'";
【解决方案3】:
$category_id = Category::select('id')->orderby('name','ASC')->get()->pluck('id')->toArray();

【讨论】:

  • 这样的长行通常受益于换行:-)
猜你喜欢
  • 2012-08-15
  • 2013-11-02
  • 2019-06-18
  • 2011-07-11
  • 2016-06-07
  • 2019-01-30
  • 2013-03-12
  • 2020-07-31
  • 2016-01-15
相关资源
最近更新 更多