2016-12-27 2 views
0

나는 stats 어플리케이션을 만들고 있는데 같은 등급의 운동 선수들을 함께 그룹화하려고합니다.Laravel : 컬렉션을 사용하여 레코드를 그룹화하려면 어떻게합니까?

나는 두 개의 테이블 : athletesathlete_position을 가지고 있습니다. 이것은 주어진 선수가 두 가지 이상의 자세로 경기를 할 수 있기 때문입니다 (다르게 평가 될 수 있기 때문).

나는 내가 찾고있는 모든 레코드를 가져 오는 쿼리를 얻을 수있다. 나는 그 레코드들을 올바른 방법으로 그룹화하는 것에 매달렸다. 여기

내가 현재 선수를 선택하고 어떻게이 큰 노력

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') 
     ->orderBy('last_name') 
     ->orderBy('athlete_position.rank') 
     ->get(); 

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

MyController.php. 제가 성취하고자하는 다음 단계는 모든 5 스타 운동 선수를 모으는 것입니다, 4.5 스타 운동 선수 모두 함께 모으는 것입니다. 이 같은

그래서 노력하고 뭔가 :

$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'); 

내가 응답을 통해 루프하려고하면 다른 응용 프로그램으로 데이터를 전송하고, 오전 :

{% for collection in athletes %} 
    {% for athlete in athletes %} 
     {{ athlete.first_name }}<br> 
    {% endfor %} 
{% endfor %}    

나는 다음과 같은 오류가 : "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"키가있는 배열의 "first_name"키가 없습니다.

의견을 보내 주셔서 감사합니다.

답변

0

이 스레드를 발견하면 다른 사람에게 도움이되기를 바랍니다. 내보기에서 데이터를 표시하는 방법과 함께 작업해야하는 쿼리가 여기 있습니다.

MyController.php (다른 시스템에) 내에서보기이어서

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


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

I 수있는이 같은 요소/그룹 (나뭇 사용)을 반복 :

... 
{% if athletes|length %} 
    {% for rating, athletes in athletes %} 
     <div>{{ rating }}</div> // 5.0 
      {% for athlete in athletes %} 
       {{ athlete.last_name }}, {{ athlete.first_name }} // Durst, Fred 
       ... 
      {% endfor %} 
    {% endfor %} 
{% endif %} 
관련 문제