简体   繁体   中英

Laravel: group results by date

In my Laravel project, I have a Match model which contains the following fields: id and starting_at timestamp.

I would like to list all matches and group them by date, just like this:

1st of June:

  1. Match id 57
  2. Match id 87

2nd of June:

  1. Match id 40
  2. Match id 99

...

Thanks !

You need to return a collection and then group items by starting_at :

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

Mind that SQL timestamp is not a valid array key, so if starting_at is such a field, then you need to change it a bit, for example:

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

this is not tested but should work....also you should probably split this up into a one to many relationship that would make this much easier.

  $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 ++;
      }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM