Loading x number of random objects?
Fri, 03/13/2009 - 03:42
Hey guys,
I'm currently loading products and limiting them to nine objects. How do I make it selects the objects randomly so I can select 9 random objects?
$this->dtrProducts->DataSource = Product::LoadAll(QQ::Clause(QQ::LimitInfo(9)));
If my code for loading the first 9 objects.
Thanks
Jason

Ability to select random rows from your database differs based upon your database vendor (MySQL, Postgre, SQL Server, ...). You'll need to write a custom SQL statement to do this - QQuery does not support this today.
Hello Jasonx
I posted a patch for this feature at http://trac.qcu.be/projects/qcubed/ticket/166
You could use like
$obj = Whatever::QueryArray(QQ::All(),
QQ::Clause(
QQ::LimitInfo(5),
QQ::Random()
)
);
This patch works very well for MySQL as Alex mention, each DBRM implement his our method, if you use otehr DBRM and you improve this patch, please share with us.
Regards
enzo
Once again I feel it is necessary to post the following link:
Do Not Use ORDER BY RAND()
In case you don't want to read it, here's the gist:
The ORDER BY RAND() (OBR) trick works okay on small tables with few rows. However, if you are thinking of applying it to a table containing more than a few hundred rows think again as what you are basically doing is telling SQL to generate a random number for EVERY row in the DB and then order by the generated random numbers.
Not clever, I think you'll agree. Exceedingly now clever on a DB with hundreds of rows that gets hit multiple times per second.
Thanks guys,
For my application I can generate the objects once a day so it will only happen once a day. I just want to rotate random products on the home page. I think the overhead will be ok. It's not a very large site.
but if only one product is needed...
$total_products = Product::CountAll();
$random_number = rand(1, $total_products);
Password::QuerySingle(
QQ::All(),
QQ::Clause(
QQ::LimitInfo(1, $random_number)
)
);