【问题标题】:How to display many_many objects in page template in Silverstripe如何在 Silverstripe 的页面模板中显示 many_many 对象
【发布时间】:2015-06-20 19:25:31
【问题描述】:

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

class TrailNotice extends DataObject {

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

这允许通过 CMS 中的复选框跨多个 TrailSection 应用单个 TrailNotice:

$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 的 TrailNotice?

【问题讨论】:

    标签: php silverstripe


    【解决方案1】:

    SilverStripe 存储许多关系RelationList,可以使用$this->RelationName()(在本例中为$this->data()->TrailNotices())访问对象。 RelationList 是DataList 的子类,因此您可以将其视为DataObject::get() 来过滤列表。

    class TrailSection_Controller extends Page_Controller {
    
      public function TrailNotices(){
        $TrailNotices = $this->data()->TrailNotices();
        return $TrailNotices;
      }
    

    在帮助部分Dataobject Relationship Management 和(更新的内容)SilverStripe Lessons 中有更多关于 SilverStripe 的 ORM 和 DataObject 关系的信息

    【讨论】:

      【解决方案2】:

      您需要在双向定义一个 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 提供的图形)。

      【讨论】:

        【解决方案3】:

        您必须在 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 的链接 Dataobject Relationship Management 中查看 Mentor 示例

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-27
          • 2013-10-31
          • 2015-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-01
          相关资源
          最近更新 更多