Laravel:按日期分组结果

时间:2014-05-20 19:51:54

标签: php laravel eloquent

在我的Laravel项目中,我有一个Match模型,其中包含以下字段:idstarting_at时间戳。

我想列出所有比赛并按日期分组,就像这样:

  

6月1日:

     
      
  1. 匹配ID 57
  2.   
  3. 匹配ID 87
  4.         

    6月2日:

         
        
    1. 匹配ID 40
    2.   
    3. 匹配ID 99
    4.         

      ...

谢谢!

2 个答案:

答案 0 :(得分:3)

您需要返回一个集合,然后按starting_at分组项目:

$matches = Match::all(); // or whatever constraints you want to apply
$matchesByDate = $matches->groupBy('starting_at');

请注意,SQL时间戳不是有效的数组键,因此如果starting_at是这样的字段,那么您需要稍微更改它,例如:

$matchesByDate = $matches->groupBy(function ($match) { return substr($match->starting_at, 0, 10);});

答案 1 :(得分:0)

这个没有经过测试但是应该可以工作....你也应该把它分成一对多关系,这会让这更容易。

  $matches = Matches::select('starting_at')->distinct()->get();
    foreach($matches as $match){
      echo $match->starting_at."<br/>";
      $ids =  Matches::where("starting_at",$match->starting_at)->lists('id');
      $count = 1;
      foreach ($ids as $id){
         echo $count.". Match id ".$id."<br/>";
         $count ++;
      }
   }
相关问题