【问题标题】:get Dataobjects from Children - SilverStripe 3.1从孩子那里获取数据对象 - SilverStripe 3.1
【发布时间】:2026-01-23 15:35:01
【问题描述】:

我有一个 GalleryHolder 和 Gallery-Pages 作为孩子。每个 Gallery-Page 都有一个 Dataobject(VisualObject) 来存储图像。

我管理它从它的画廊页面上的 GalleryPage 中获取 3 张随机图像,并从 GalleryHolder 页面上的所有画廊中获得 3 张随机图像。

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

这是我的代码, 谁能告诉我该怎么做?

【问题讨论】:

    标签: php silverstripe


    【解决方案1】:

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

    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;
    }
    

    // 编辑作为对您的 cmets 的响应:

    如果你希望它按画廊分组,我会一起做不同的(忘记上面的代码,只需执行以下操作):

    把它放到你的 Gallery 类中:

    // 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 或任何其他属性
    或者你可以使用&lt;% with %&gt; 来确定它的范围:

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

    【讨论】:

    • 嗨,谢谢,这完成了这项工作。但知道我还有另一个问题。如何获取每个画廊的名称?
    • 你想在每张图片上显示画廊的标题,还是想按画廊对它们进行分组以获得某种标题?
    • 我想要主画廊的标题。所以画廊 1 显示了 3 个随机图像和画廊标题,画廊 2 显示了 3 个随机图像和画廊标题,依此类推
    • 所以他们按画廊分组,我明白了。我稍后会用代码示例更新答案,我现在很忙
    • 噢! :D 在我写这个问题之前我使用了相同的功能。但我把它放到了 Gallery_Controller 中。而且它不起作用。谢谢