LoginSignup
15
12

More than 3 years have passed since last update.

laravel eloquent withでソートしたい時

Last updated at Posted at 2019-09-10

初心者が書いた記事ですので、ご容赦ください。

結論

一度、普通に取得して、collectionのsortBy()を使用すればできます。

前提

いい例が思いつきませんが。hasOneとbelongToの関係のものがあるとします。
仮に boyfrindsテーブルgirlfrindsテーブル とします。
それぞれ nameカラム を持っております。

model側でリレーションシップは設定してあるとします。

実現したいこと

boyfrindsgirlfrinds.name でソートして取得したい

始めにやったこと(上手くいきませんでした)

$boyfrinds = Boyfrind::where('boyfrind_id', $boyfrind_id)
    ->with('girlfrind')
    ->orderBy('girlfrind.name', 'asc')
    ->get();

解決しました

$boyfrinds = Boyfrind::where('boyfrind_id', $boyfrind_id)
    ->with('girlfrind')
    ->get();

$boyfrinds = $boyfrinds->sortBy('girlfrind.name')->values();

参考
https://laravel.com/docs/6.0/collections#method-sortby

15
12
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
15
12