Jump to:

17452 Posts in 4473 Topics by 1971 members

Archive

SilverStripe Forums » Archive » Get random object

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

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

Page: 1 2 3
Go to End
Author Topic: 9303 Views
  • Double-A-Ron
    Avatar
    Community Member
    604 Posts

    Get random object Link to this post

    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 Link to this post

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

    You could try something like that.

  • Double-A-Ron
    Avatar
    Community Member
    604 Posts

    Re: Get random object Link to this post

    Mean. Exactly what I was looking for.

    Cheers mate.
    Aaron

  • Double-A-Ron
    Avatar
    Community Member
    604 Posts

    Re: Get random object Link to this post

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

  • Re: Get random object Link to this post

    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.

  • Double-A-Ron
    Avatar
    Community Member
    604 Posts

    Re: Get random object Link to this post

    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.

  • moloko_man
    Avatar
    Community Member
    72 Posts

    Re: Get random object Link to this post

    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?

  • Double-A-Ron
    Avatar
    Community Member
    604 Posts

    Re: Get random object Link to this post

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

    9303 Views
Page: 1 2 3
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.