投稿数ですべてのユーザーを並べ替えることができます。 Like:Laravelの投稿の最大数でユーザーを並べ替える方法
User1(100 posts)
User2(90 posts)
User3(80 posts)
これはどのようにしてlaxvel elequont関係で行うことができますか?
投稿数ですべてのユーザーを並べ替えることができます。 Like:Laravelの投稿の最大数でユーザーを並べ替える方法
User1(100 posts)
User2(90 posts)
User3(80 posts)
これはどのようにしてlaxvel elequont関係で行うことができますか?
使用withCount
ポストは関係をロードせずにカウントを取得し、posts_count
を使用して結果をソートします。必要に応じて追加条件を適用することもできます。ボーナスとして、各ユーザーの投稿数を取得します。
$users = User::withCount('posts')
->orderBy('posts_count', 'desc')
->get();
あなたはこのようにそれを行うことができます。
$users = User::with('posts')->get()-
>sortBy(function($users)
{
return $users->posts->count();
});
はこれを試してみてください:
$data = User::select(DB::raw('users.*, count(*) as total_posts'))
->join('posts', 'users.id', '=', 'posts.user_id')
->groupBy('user_id')
->orderBy('total_posts', 'desc')
->get();
ありがとうございました – Harry