首页 文章

SilverStripe:使用 has_many 关系对 DataObject 进行排序

提问于
浏览
1

在 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()

我希望它们按最早的日期排序。

哪种方式最好实现这一目标?

1 回答

  • 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();
    
    ?>
    

相关问题