3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】リレーション先のテーブルでソートする

3
Last updated at Posted at 2022-03-14

この記事は個人ブログに移行しました。最新情報はブログ版をご覧ください。

要点

  • リレーション先のレコード数でソートしたい — withCount('リレーション名')で取得してリレーション名 countを指定する。
  • リレーション先のカラムでソートしたい — withCount() のような良い感じの関数がなく、joinしてあげる必要あり。 例)古参ユーザーが投稿した順 ※selectは必要なければ指定不要 テーブル名はモデル内に隠蔽しておきたい場合は Post::make()- getTable() で取得できる。
  • 中間テーブルのカラムでソートしたい — withPivot を使う。

もっと詳しく

  • ブログではコード全文や補足資料を継続的に更新しています
  • 気になる点があればコメントください🙌
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?