在Laravel 4中对集合进行排序

时间:2013-12-05 20:52:28

标签: laravel eloquent

我在日历中有日期并且使用下面的方式访问它们,它们与Category表有一个类别关系,并且与CalEvent表有关系。

$cal_dates = CalDate::whereBetween('date', array($from, $to))
                ->orderBy('date')
                ->orderBY('start')
                ->get();

这将返回按范围内的开始日期排序的列表。到目前为止一切都很好,返回的行如下所示,我可以访问Category和CalEvent,即$cal_date->CalEvent->description

{
 "id":"406",
 "cal_event_id":"77",
 "start":"00:00:00",
 "finish":"00:00:00",
 "date":"2014-04-06",
 "created_by":"0",
 "updated_by":"0",
 "created_at":"2013-09-21 04:43:25",
 "updated_at":"2013-09-21 04:43:25"
}

我需要的是一个像下面这样的对象,我的视图与CategoryCal_Dates表的关系完好无损:

 cal_dates
    '12th Feb 2014'
        'Array of dates related to category 1 for 12th Feb'
        'Array of all other dates not related to category 1 for 12th Feb'
    '13th Feb 2014'
        'Array of dates related to category 1 for 13th Feb'
        'Array of all other dates not related to category 1 for 13th Feb'
    ...

任何建议都非常感谢...

1 个答案:

答案 0 :(得分:4)

试试这个:

$cal_dates = $cal_dates->sortBy(function($cal_date)
{
    return $cal_date->date;
});

或修改您的查询:

$cal_dates = CalDate::with('category')
                ->whereBetween('date', array($from, $to))
                ->orderBy('date')
                ->orderBY('start')
                ->get();

然后在您的视图中,您可以访问以下关系:

@foreach($cal_dates as $cal_date)

   <li> {{ $cal_date->date }} </li>
   <!-- category data -->
   <li> {{ $cal_date->category->something }}

@endforeach