在SilverStripe中,我有一个事件数据对象
class Event extends DataObject {
private static $db = array(
'Name' => 'Text'
);
private static $has_many = array(
'EventDates' => 'EventDate'
有很多活动日期:
class EventDate extends DataObject {
private static $db = array(
'Day' => 'Date',
'StartTime' => 'Varchar',
'EndTime' => 'Varchar'
);
现在,如果我查询页面上的所有事件,如
Event::get()
我希望他们按照最早的日期排序。
哪种方式最好实现这一目标?
答案 0 :(得分:2)
您可以使用默认排序规则在DataObject类上定义静态属性:
<?php
class EventDate extends DataObject {
…
// This also effects the default sorting of `has_many` related Events.
private static $default_sort = "\"Day\" ASC";
}
?>
现在
<?php
// first we pick a Event object, for instance by a (given) $id
$event = Event::get()->byId($id);
// because the default sort ist Day the attached `EventDate` will now be sorted by `Day` if you don't specify otherwise
$events = $event->EventDates();
// will return the earliest Event (of course you don't filter events here which are in the past).
$firstEvent = $events->First();
// if you then want to sort differently at some place, you can call ->sort() on the list:
$event = Event::get()->byId($id);
$events = $event->EventDates()->sort('LastEdited', 'DESC');
$lastEditedEvent = $events->First();
?>