17488 Posts in 4473 Topics by 1978 members
| Go to End | Next > | |
| Author | Topic: | 8692 Views |
-
Get random object

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 -
Re: Get random object

22 July 2008 at 11:54pm
DataObject::get_one('Tour', null, false, 'RAND()');
You could try something like that.
-
Re: Get random object

22 July 2008 at 11:58pm
Mean. Exactly what I was looking for.
Cheers mate.
Aaron -
Re: Get random object

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.
-
Re: Get random object

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.
-
Re: Get random object

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?
-
Re: Get random object

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()');
}
}
| 8692 Views | ||
| Go to Top | Next > |


