mardi 27 décembre 2016

Laravel: How can I group records together using a collection?

I am creating a stats application and I am trying to group athletes of the same rating together.

I have two tables: athletes and athlete_position. This is because any given athlete can play (be rated differently) for more than one position.

I am able to get a query that gets all of the records I am looking for, I am just hung up on grouping them together the correct way.

Here is how I am currently selecting the athletes:

MyController.php

public function ratings($year, $position_id) {
    $athletes = Athlete::where('graduation_year', $year)
        ->join('athlete_position', 'athlete_position.athlete_id', '=', 'athletes.id')
        ->where('athlete_position.position_id', '=', $position_id)
        ->groupBy('athlete_position.rating')
        ->join('evaluations', 'evaluations.athlete_id', 'athletes.id')
        ->whereNotNull('evaluations.comments')
        ->where('evaluations.status', 'published')
        ->orderBy('last_name')
        ->orderBy('athlete_position.rank')
        ->get();

    return response()->json(['data' => $athletes], 200);
}

This is working great. The next step I am trying to accomplish is to group all 5 star athletes together, all 4.5 star athletes together and so on.

So I am trying something like this:

 $collection = collect(
     Athlete::where('graduation_year', $year)
     ->join('athlete_position', 'athlete_position.athlete_id', '=', 'athletes.id')
     ->where('athlete_position.position_id', '=', $position_id)
 )->groupBy('athlete_position.rating');

I am sending the data to another application, and when I try to loop through the response:

            

I get the following error: Key "first_name" for array with keys "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10" does not exist.

Thank you for any suggestions!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire