简单的解决方案是只教你的孩子
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 或任何其他属性
或者你可以使用<% with %> 来确定它的范围:
<% with $RandomObject %>
$ID<br>
$Visual
<% end_with %>