2013-05-07 83 views
1

我有一個$事件對象是得到了一堆在使用查詢生成器我的數據庫的各種表的結果在Laravel 4.看到這裏http://paste.laravel.com/qIj周Laravel處開始4

我想在分開的結果因此當我在視圖中輸出它們時,它會根據事件表的start_date字段中的信息按周分組所有內容。

任何想法如何最好地實現這一點?乾杯。

回答

4

我平時做這樣的事情:

<?php 
// Event model 
public function getAllByWeek() { 
    $events = static::orderBy('created_at', 'DESC')->get(); 
    $orderedEvents = array(); 

    foreach ($events as $event) { 
     $date = new \DateTime($event->created_at); 
     $weekCategory = $date->format('oW'); 
     $weekFormatted = $date->format('W'); 

     if (! array_key_exists($weekCategory, $orderedEvents)) { 
      $orderedEvents[$weekCategory] = (object) array(
       'week' => $weekFormatted, 
       'events' => array(), 
      ); 
     } 

     $orderedEvents[$weekCategory]->events[] = $event; 
    } 

    return $orderedEvents; 
} 

// Controller 
$orderedEvents = Event::getAllByWeek(); 

// View 
@foreach ($orderedEvents as $eventsHolder) 

    {{ $eventsHolder->week }} 

    @foreach ($eventsHolder->events as $event) 

     // content output 

    @endforeach 

@endforeach