Hi all.
Anyone have any ideas how I can pull a random object from the database? I have a Tour object and I am trying to pull one out at random for the homepage featured tour seen on the right here: http://www.vivaexpeditions.com.
Cheers
Aaron
This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.
Please use forum.silverstripe.org for any new questions
(announcement).
The forum archive will stick around, but will be read only.
You can also use our Slack channel
or StackOverflow to ask for help.
Check out our community overview for more options to contribute.
Hi all.
Anyone have any ideas how I can pull a random object from the database? I have a Tour object and I am trying to pull one out at random for the homepage featured tour seen on the right here: http://www.vivaexpeditions.com.
Cheers
Aaron
DataObject::get_one('Tour', null, false, 'RAND()');
You could try something like that.
Mean. Exactly what I was looking for.
Cheers mate.
Aaron
Actually, it pulls out an empty object sometimes....
That's odd - the only way i think of where that could happen is if you have empty objects in your DB - basically all it does is a SELECT * FROM table LIMIT 1 ORDER BY RAND() - so it shouldn't throw up any empty objects.
Hmm weird.
The only way I was able to stop it is by checking on the of the numeric fields in that table to make sure it is bigger than zero.
return DataObject::get_one('Tour', 'TourLengthDays>0', false, 'RAND()');
Maybe a blank record in there? I can't find it in the Tours or Tours_Live table.
I'm trying to pull in a random product into the "homepage" only and so far I'm at a loss at where I need to insert the following code:
DataObject::get_one('products', null, false, 'RAND()');
Can you shed some light on how you did yours?
In your HomePage.php file under mysite/code (as long as you aren't using the tutorial directory instead)
Make a controller and add a getRandomObject() function like so:
class HomePage_Controller extends Page_Controller {
// Get random object
function getRandomObject() {
return DataObject::get_one('products', null, false, 'RAND()');
}
}