2016-09-28 320 views
0

我所有的比賽由起始日期排序的,但我想要的日期不顯示始終,而不是按日期像下面分開隊:集團通過雄辯laravel

$matches=Match::orderBy('start_date','desc')->get(); 
foreach($matches as $match) 
{ 
     $match->team1; 
     $match->team2; 
     $match->start_date; 
} 

這給:

Team1 
Team2 
2016-9-28 
Team3 
Team4 
2016-9-28 
Team5 
Team6 
2016-9-28 
... 

相反,我想

2016-9-28 
Team1 
Team2 
Team3 
Team4 
Team5 
Team6 
.... 

2016-9-29 
Team1 
Team2 
Team3 
.... 

GROUP_BY起始日期可能?

回答

2

使用groupBy來對最終的集合進行分組。

$matchGroups = Match::orderBy('start_date','desc')->get()->groupBy('start_date'); 

如果start_date是碳日期,你可以嘗試

$matchGroups = Match::orderBy('start_date','desc')->get()->groupBy(function($item) { 
    return $item->start_date->format('Y-n-j'); 
}); 

而且在你看來

@foreach ($matchGroups as $startDate => $matches) { 
    {{ $startDate }} 

    @foreach ($matches as $match) { 
     {{ $match->team1 }} 
     {{ $match->team2 }} 
    @endforeach 
@endforeach 
+0

$ startDate沒有給出日期。還有'foreach($匹配$匹配)'給出錯誤。 – Steve

+0

@Steve查看更新的答案。 'groupBy'應該在'get'之後出現 – chanafdo

1

嗯..你可以嘗試

$matches = Match::select(DB::raw('GROUP_CONCAT(team) AS teammate'), 'start_date') 
      ->groupBy('start_date'); 
      ->get() 
      ->toArray(); 

指定者是可選結果應該是:

array:2 [ 
    0 => array:2 [ 
     "start_date" => "2016-9-28" 
     "teammate" => "Team1,Team2, Team3, Team4, Team5, Team6" 
    ] 
    1 => array:2 [ 
     "start_date" => "2016-9-29" 
     "teammate" => "Team1,Team2, Team3" 
    ] 
] 

這是你尋找的結果嗎?