Packy
Packy

Reputation: 3573

groupBy keep individual entries

I am making a scoring system and I am trying to group scores together and loop trough them so if you tie you get the same place. Example:

score = 100
score = 100
score = 90

the first 2 scores should place 1st and the third score be 2nd.

so I tried

 $submissions = Submission::where([
                                        ['league_id', $league->id ],
                                        ['challenge_id', $challenge->id]
                                    ])
                                    ->orderBy('class', 'desc')
                                    ->orderBy('user_score', 'asc')
                                    ->groupBy('user_score')
                                    ->get();

then I loop:

if( count($submissions) > 0 )
{
      foreach ( $submissions as $index => $submission_group ) {
          if( count($submission_group) > 0 ){

              foreach ( $submission_group as $i => $submission {
                  $submission->points = $i+ 1;
                  $submission->save();
              }
          } 
      }                                
}

the trouble is $submissions is returning an array of 2 entries ( for just the 1st and 3rd). I would imagine it would return 2 arrays. like so:

[
  submission[],
  submission[],
],
[
 submission[],
]

If I remove groupBy I get all 3 entries. It appears it lumps the two 100 scores as 1 entry and the 90 as another entry

Upvotes: 1

Views: 37

Answers (1)

AH.Pooladvand
AH.Pooladvand

Reputation: 2059

I'm not sure if it's relevant but I suppose that groupBy() method should be use after get() method.

Upvotes: 1

Related Questions