0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel】特殊な条件で並び替えしたクエリを実行する方法

Posted at

概要

$idsの順番通りにクエリの結果を並び替えて取得したかったが少し詰まったのでやり方を紹介する

元々の処理

$ids = [3, 2, 4];

$users = User::query()
    ->whereIn('id', $ids)
    ->pluck('name', 'id')
    ->toArray();

期待する結果

[
    3 => "hoge",
    2 => "fuga",
    4 => "hogehoge",
];

やり方

SQLのFIELD 関数を利用して任意の並び順を指定します


$ids = [3, 2, 4];
$sortIds = implode(', ', $ids);

$contents = TrainingContent::query()
    ->whereIn('id', $contentIds)
    ->orderByRaw("FIELD(id, $sortOption)")
    ->pluck('title', 'id')
    ->toArray();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?