the simple solution is to just foreach your children
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;
}
// EDIT as reponse to your comments:
if you want it to be grouped by gallery, I would do it different all together (forget the above code and just do the following):
put this in your Gallery class:
// File: Gallery.php
class Gallery extends Page {
...
public function getRandomPreview($num=3) {
return $this->GalleryImages()
->filter(array('Visibility' => 'true'))
->sort('RAND()')
->limit($num);
}
}
and then in template of the Parent (the GalleryHolder
) you just call that function:
// 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 %>
// EDIT another comment asks for an exaple of a single dataobject:
if you just want 1 random gallery image, use the following:
// 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();
}
}
and then in template you access the method directly:
$RandomObject.ID
or $RandomObject.Visual
or any other property
or you can use <% with %>
to scope it:
<% with $RandomObject %>
$ID<br>
$Visual
<% end_with %>