从子项获取数据对象 - SilverStripe 3.1.


get Dataobjects from Children - SilverStripe 3.1

我有一个GalleryHolder,里面有Gallery-Pages作为孩子。每个图库页面都有一个数据对象(VisualObject)来存储图像。

我设法从其图库页面上的图库页面获取 3 张随机图像

,并从图库持有人页面上的所有图库中获取 3 张随机图像。

但我想要的是 GalleryHolder 页面上显示的每个图库的 3 张随机图像。

这是我的代码,有人可以告诉我该怎么做吗?

  • 画廊持有人: http://sspaste.com/paste/show/525e4b9134940
  • 图库: http://sspaste.com/paste/show/525e4bb25f236
  • 可视对象:http://sspaste.com/paste/show/525e4bd3cdfff

简单的解决方案就是只为你的孩子

public function getRandomPreviewForAllChildren($numPerGallery=3) {
    $images = ArrayList::create();
    foreach($this->data()->Children() as $gallery) {
        $imagesForGallery = $gallery->GalleryImages()
            ->filter(array('Visibility' => 'true'))
            ->sort('RAND()')
            ->limit($numPerGallery);
        $images->merge($imagesForGallery);
    }
    return $images;
}

编辑作为对您的评论的回应:

如果您希望按图库对其进行分组,我会一起做不同的事情(忘记上面的代码,只执行以下操作):

把它放在你的图库类中:

// File: Gallery.php
class Gallery extends Page {   
    ...
    public function getRandomPreview($num=3) {
        return $this->GalleryImages()
            ->filter(array('Visibility' => 'true'))
            ->sort('RAND()')
            ->limit($num);
    }
}

然后在父级(GalleryHolder)的模板中,您只需调用该函数:

// File: GalleryHolder.ss
<% loop $Children %>
    <h4>$Title</h4>
    <ul class="random-images-in-this-gallery">
        <% loop $RandomPreview %>
            <li>$Visual</li>
        <% end_loop %>
    </ul>
<% end_loop %>

编辑另一条评论要求单个数据对象的实例:

如果您只需要 1 个随机图库图像,请使用以下内容:

// File: Gallery.php
class Gallery extends Page {   
    ...
    public function getRandomObject() {
        return $this->GalleryImages()
            ->filter(array('Visibility' => 'true'))
            ->sort('RAND()')
            ->first();
        // or if you want it globaly, not related to this gallery, you would use:
        // return VisualObject::get()->sort('RAND()')->first();
    }
}

然后在模板中直接访问该方法:
$RandomObject.ID$RandomObject.Visual或任何其他财产
或者,您可以使用<% with %>来限定其范围:

<% with $RandomObject %>
    $ID<br>
    $Visual
<% end_with %>