LoginSignup
3
2

More than 3 years have passed since last update.

Laravel 多対多関係で使っている中間テーブルの created_at, updated_at などのカラムで並べ替える

Last updated at Posted at 2020-02-22

前提

userspostsfavoritesを中間テーブルとして多対多の関係になっています。

TL;DR

public function favorite_posts()
{
    return $this
        ->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')
        ->withPivot(['created_at', 'updated_at', 'id'])
        ->orderBy('pivot_updated_at', 'desc')
        ->orderBy('pivot_created_at', 'desc')
        ->orderBy('pivot_id', 'desc');
}

簡単に説明

withPivot()を使用することで中間テーブルのカラムを参照できます。
withPivot()の引数にorderby()に使用したいカラムを配列形式で指定します。
orderBy()の第1引数には'pivot_' + カラム名の形式で指定します。

確認

favorite_posts()の呼び出し元の前後に以下を追記し、実際に流れているSQLを確認します。

DB::enableQueryLog();
$user->favorite_posts;
dd(DB::getQueryLog());
array:1 [
  0 => array:3 [
    "query" => "select `posts`.*, `favorites`.`user_id` as `pivot_user_id`, `favorites`.`post_id` as `pivot_post_id`, `favorites`.`created_at` as `pivot_created_at`, `favorites`.`updated_at` as `pivot_updated_at`, `favorites`.`id` as `pivot_id` from `posts` inner join `favorites` on `posts`.`id` = `favorites`.`post_id` where `favorites`.`user_id` = ? order by `pivot_updated_at` desc, `pivot_created_at` desc, `pivot_id` desc"
    "bindings" => array:1 [
      0 => 1
    ]
    "time" => 0.37
  ]
]

中間テーブルfavoritesupdated_atcreated_atidでorderbyされているのが確認できました:clap:

参考

https://readouble.com/laravel/5.8/ja/eloquent-relationships.html
https://stackoverflow.com/questions/26551078/how-to-order-by-pivot-table-data-in-laravels-eloquent-orm/50767168

3
2
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
2