Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

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.

Archive /

Our old forums are still available as a read-only archive.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo

Get random object


Go to End


20 Posts   11862 Views

Avatar
Double-A-Ron

Community Member, 607 Posts

22 July 2008 at 11:39pm

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

Avatar
Grayzag (aka ajshort)

29 Posts

22 July 2008 at 11:54pm

DataObject::get_one('Tour', null, false, 'RAND()');

You could try something like that.

Avatar
Double-A-Ron

Community Member, 607 Posts

22 July 2008 at 11:58pm

Mean. Exactly what I was looking for.

Cheers mate.
Aaron

Avatar
Double-A-Ron

Community Member, 607 Posts

23 July 2008 at 12:01am

Actually, it pulls out an empty object sometimes....

Avatar
Grayzag (aka ajshort)

29 Posts

23 July 2008 at 12:29am

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.

Avatar
Double-A-Ron

Community Member, 607 Posts

23 July 2008 at 8:04am

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.

Avatar
moloko_man

Community Member, 72 Posts

2 September 2008 at 4:18pm

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?

Avatar
Double-A-Ron

Community Member, 607 Posts

2 September 2008 at 4:25pm

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()');
	}
	
}

Go to Top