LoginSignup
23
19

More than 3 years have passed since last update.

【Laravel】取得時にリレーションのカウントでOrderByする方法

Last updated at Posted at 2017-03-25

Laravelでは、WithCountメソッドでリレーションの数を取得できます。
https://readouble.com/laravel/6.x/ja/eloquent-relationships.html#counting-related-models

// RecipeにFavoriteのHasManyリレーションがある場合
Recipe::withCount('favorites')
    ->orderBy('favorites_count', 'desc')
    ->limit(3)
    ->get();

内部ではサブクエリが発行されています。

"select `recipes`.*, (select count(*) from `recipe_favorites` where `recipes`.`id` = `recipe_favorites`.`recipe_id`) as `favorites_count` from `recipes` order by `favorites_count` desc limit 3"
23
19
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
23
19