LoginSignup
2
1

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-03-14

リレーション先のレコード数でソートしたい

withCount('リレーション名')で取得してリレーション名_countを指定する。

例)コメントの多い順
Post::withCount('comments')
->orderBy('comments_count', 'desc')

リレーション先のカラムでソートしたい

withCount() のような良い感じの関数がなく、joinしてあげる必要あり。

例)古参ユーザーが投稿した順
Post::select(['posts.*', 'users.created_at'])
->join('users', 'users.id', '=', 'posts.user_id')
->orderBy('users.created_at')

※selectは必要なければ指定不要

テーブル名はモデル内に隠蔽しておきたい場合は Post::make()->getTable() で取得できる。※参考

例)古参ユーザーが投稿した順(テーブル名ベタ書きは嫌)
Post::join(
    User::make()->getTable(),
    User::make()->getTable().'.id', '=', Post::make()->getTable().'.user_id'
)
->orderBy(User::make()->getTable().'.created_at')

うーん、、
withColumn('user', 'created_at') のような関数あればいいのにな。

中間テーブルのカラムでソートしたい

withPivot を使う。

とある投稿のいいねしたユーザー一覧(いいねした順)
class Post extends Model
{
    public function likeUsers()
    {
        // エイリアス指定しないとpivot_created_atになるので、わかりやすい名前をつけるのおすすめ
        return $this->belongsToMany('User', 'post_user_like')->withPivot('created_at as like_at');
    }
}

$post->likeUsers()->orderBy('like_at');
2
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
2
1