A
A
Alexander Shapoval2016-06-07 09:15:48
Laravel
Alexander Shapoval, 2016-06-07 09:15:48

Laravel, grouping via groupby(). How to return an array containing id?

Good afternoon.
There is a query
$ret = User::select('id')->groupBy('age')->get();
Groups norms, but you need to get arrays with user ids as a result:
[1,3,8,9],[2,4,5,7],[6,10].....
Tell me how to do this. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Semenko, 2016-06-07
@AlexanderShapoval

$users = User::select(DB::raw('GROUP_CONCAT(id) as id'))->groupBy('age')->get();
$groups = $users->map(function ($item, $key) {
  return explode(',', $item['id']); // Возможно здесь ошибся
});

D
D', 2016-06-07
@Denormalization

Something like this (crutch):

$ret = User::select('id', 'age')->get()->groupBy('age')->map(function ($item) { return $item->pluck('id'); } )->toArray();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question