0
0

sortBy()とorderBy()

Posted at

sortBy()

指定したキーでコレクションを並べ替える

// モデルからデータを取得
$users = User::all();

// コレクションを並べ替える
$sortedUsers = $users->sortBy('age');

orderBy()

データベースからデータを取得する際に指定したカラムで並べ替える

// クエリビルダーでデータを並べ替えながら取得
$users = User::orderBy('age', 'asc')->get();

違いとしては対象が
sortBy()はLaravelのコレクション
orderBy()はLaravelのクエリビルダ
である点

orderBy()はよく使っていたが、今回データを取得した後に並び替える必要があったのでsortBy()を使用したのでメモ

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