【问题标题】:Laravel Eloquent whereIn return in order givenLaravel Eloquent whereIn 按给定的顺序返回
【发布时间】:2021-09-06 21:34:30
【问题描述】:

我正在尝试按 whereIn 传递的数组的顺序对集合进行排序

我的代码:

Posts::whereIn('id', [80, 40, 30, 100])->get()

我希望集合以 80、40、30、100 的顺序返回 id 的帖子,但它按升序排序为 30、40、80、100。我如何按顺序接收结果我希望吗?

【问题讨论】:

  • $user->recent_posts()->latest('post_id')->get();您可以直接使用它来获取用户帖子。
  • 为您的问题添加更多详细信息
  • 使用 latest() 会给我最新的帖子,而不是显示顺序的所有帖子。
  • 我已经改写了我的问题,以明确我的问题是什么

标签: laravel eloquent where-in


【解决方案1】:

试试这个查询 -

$ids = [80, 40, 30, 100];
$implodedIds = implode(',', $ids);

Posts::whereIn('id', $ids)->orderByRaw(DB::raw("FIELD(id, $implodedIds)"))->get();

【讨论】:

    猜你喜欢
    • 2016-09-03
    • 2017-04-01
    • 2017-03-17
    • 2020-01-05
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多