如何在 Silverstripe 的页面模板中显示 many_many 个对象

How to display many_many objects in page template in Silverstripe

我们的站点有一个名为 "TrailNotice" 的对象,它与页面类型 "TrailSection" 有 many_many 关系。

class TrailNotice extends DataObject {

  private static $many_many = array(
    'TrailSections' => 'TrailSection'
  );

这允许通过 CMS 中的复选框将单个 TrailNotice 应用于多个 TrailSections:

$fields->addFieldToTab('Root.Main', new CheckboxSetField('TrailSections', 'Applies to which trail sections?', DataObject::get('TrailSection')->map('ID', 'Title')));

如何在 TrailSection 页面控制器中显示附加到 TrailSection 的 TrailNotices?

我从以下代码开始:

class TrailSection_Controller extends Page_Controller {

  public function TrailNotices(){
    $TrailNotices = DataObject::get('TrailNotice');
    return $TrailNotices;
  }

但是这将获取所有TrailNotice 对象。如何过滤它们以便仅显示附加到 TrailSection 的 TrailNotices?

SilverStripe 存储 many_many 关系 RelationList that can be access on the object using $this->RelationName() (in this case $this->data()->TrailNotices()). The RelationList is a subclass of DataList,因此您可以像 DataObject::get() 一样对待它来过滤列表。

class TrailSection_Controller extends Page_Controller {

  public function TrailNotices(){
    $TrailNotices = $this->data()->TrailNotices();
    return $TrailNotices;
  }

在帮助部分有更多关于 SilverStripe 的 ORM 和 DataObject 关系的信息 Dataobject Relationship Management and (newer content) SilverStripe Lessons

你需要在两个方向上定义一个many_many,然后你可以从两侧访问它。一侧有 $many_many

class TrailNotice extends DataObject {

  private static $many_many = array(
    'TrailSections' => 'TrailSection'
  );

另一方面你必须定义$belongs_many_many

class TrailSection extends DataObject {

  private static $belongs_many_many = array(
    'TrailNotices' => 'TrailNotice'
  );

然后在您的模板中,您可以调用关系列表并对其进行循环:

<% loop $TrailNotices %>
    $Title
<% end_loop %>

查看了解所有可能的关系(感谢@nightjar 提供图形)。

您必须在您的 TrailSection 模型中实现一个 $belongs_many_many,类似于:

class TrailSection extends DataObject {

  private static $belongs_many_many = array(
    'TrailNotices' => 'TrailNotice'
  );

}

然后您可以简单地将 $TrailNotices 循环到 TrailSection.ss 模板中,而无需对您的控制器进行任何操作:

<% loop $TrailNotices %>
    $Title<br>
<% end_loop %>

您可以查看 Stephen 的 Mentor 示例 link Dataobject Relationship Management