M
M
mskr2019-06-17 23:38:09
Laravel
mskr, 2019-06-17 23:38:09

How to sort a grouped collection?

Laravel 5.5
There is a collection of different types of models:

модель Участник [
type = {школьник или студент}
year = год
olimp_id = связь с моделью олимпиады
rating = результат в баллах
position = место в рейтинге
]

It is necessary to put down each of his place in the ranking for the year-Olympiad-category-rating.
It seems that groupBy() is ideal, but at the last stage it groups the models according to their rating into discord: sorting through sortBy() does not help, because of this, naturally, the position is incorrect. Can you tell me what I can come up with or maybe I went the wrong way?
$rating = $this->rating->groupBy(['year','olimp_id', 'model_type', 'rating']);

$rating->each(function ($year_item, $year) {
  $year_item->each(function ($olimp_item) {
    $olimp_item->each(function ($model_type_item) use(&$position) {
    $position = 0;
      $model_type_item->each(function ($rating_item) use(&$position) {
        $position++;
        $rating_item->each(function ($model) use($position) {
          $model->update(['position' => $position]);
        });
      });
    });
  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Si-Dge, 2019-06-18
@mskr

$model_type_item->sortByDesc(function ($item) {
  return $item->first()->rating;
})->each(function ($rating_item) use(&$position) {

https://laracasts.com/discuss/channels/laravel/sor...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question