I have a SQL table with only two columns: "nameid" and "name". I want to get a random name out of the database.
Before I did this via:
$result = mysql_query("SELECT * FROM nametable",$db);
$number = mysql_num_rows($result);
$random = rand(1,$number);
list($name) = mysql_fetch_row(mysql_query("SELECT name FROM nametable WHERE nameid=$random",$db));
How can I do the same with Doctrine?
MySQL has a function for generating random floating point values RAND()
. When sorting by this, the names will be randomly-ordered. After this, you simply select the first, randomly-ordered name.
SELECT name FROM nametable ORDER BY RAND() LIMIT 1
With Doctrine, this could be done using
$name = Doctrine::getTable('nametable')
->createQuery()
->select('name')
->orderBy('RAND()')
->fetchOne();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.