简体   繁体   中英

Laravel 5.6 groupBy on collection doesn't work

GroupBy just doesn't work on collection in Laravel 5.6, it is very annoying when simple things which supposed to work not wirking...

$users = Game::orderBy('game_count', 'desc')->get();

$users_grouped = $users->groupBy('user_id');

As you might guess $users_grouped contains the same collection as $users with the same repeating user_id values.

I don't get why it doesn't work as expected and how to fix it?

At least GROUP BY works with raw DB select hopefully.. But I want to use Eloquent..

You're confusing eloquent's query builder with collections. They are not the same thing.

groupBy on a query builder instance will use an SQL GROUP BY and give one aggregated result for the column(s) you are grouping on.

groupBy on a collection instance will return a new collection that groups all collected items by the given key's value.

https://laravel.com/docs/5.6/collections#method-groupby

If you want to use the query builder's groupBy method, chain it before the get() :

$users = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();

get() executes the query and returns the collection of records.

如果要按user_id对查询进行分组,只需在get()之前进行groupBy,如下所示:

$users = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();

The rows will be the same. You should make two querys:

$users = Game::orderBy('game_count', 'desc')->get();
$users_grouped = Game::orderBy('game_count', 'desc')->groupBy('user_id')->get();

临时解决方案是原始SQL查询:

$users_grouped  = DB::select('SELECT COUNT(id) AS theCount, `user_id` from `quiz_games` GROUP BY `user_id` ORDER BY theCount DESC');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM