首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从儿童中获取数据对象- SilverStripe 3.1

从儿童中获取数据对象- SilverStripe 3.1
EN

Stack Overflow用户
提问于 2013-10-16 08:27:41
回答 1查看 2.2K关注 0票数 0

我小时候有一个画廊版的GalleryHolder。每个图库-页面都有一个数据对象(VisualObject)来存储图像.

我设法从GalleryPage的画廊页面上获得了3张随机图像,从GalleryHolder页面上的所有画廊获得了3张随机图像。

但我想要的是3个随机的图片,每个画廊显示在GalleryHolder页面。

这是我的密码,有人能告诉我怎么做吗?

  • GalleryHolder:http://sspaste.com/paste/show/525e4b9134940
  • 画廊:http://sspaste.com/paste/show/525e4bb25f236
  • VisualObject:http://sspaste.com/paste/show/525e4bd3cdfff
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-16 11:51:31

简单的解决办法就是教育你的孩子

代码语言:javascript
复制
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;
}

//编辑回复您的评论:

如果您希望按图库对其进行分组,我会将其组合在一起(忘记上面的代码,只需执行以下操作):

把这个放到你的画廊课上:

代码语言:javascript
复制
// File: Gallery.php
class Gallery extends Page {   
    ...

    public function getRandomPreview($num=3) {
        return $this->GalleryImages()
            ->filter(array('Visibility' => 'true'))
            ->sort('RAND()')
            ->limit($num);
    }
}

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

代码语言:javascript
复制
// 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 %>

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

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

代码语言:javascript
复制
// 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 %>对其进行范围分析:

代码语言:javascript
复制
<% with $RandomObject %>
    $ID<br>
    $Visual
<% end_with %>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19398514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档