简体   繁体   English

Doctrine:从名字表中获取一个随机名字

[英]Doctrine: Get a random name from a table of names

I have a SQL table with only two columns: "nameid" and "name".我有一个只有两列的 SQL 表:“nameid”和“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?我怎样才能对 Doctrine 做同样的事情?

MySQL has a function for generating random floating point values RAND() . MySQL 有一个 function 用于生成随机浮点值RAND() When sorting by this, the names will be randomly-ordered.按此排序时,名称将随机排序。 After this, you simply select the first, randomly-ordered name.在此之后,您只需 select 第一个随机排序的名称。

SELECT name FROM nametable ORDER BY RAND() LIMIT 1

With Doctrine, this could be done using对于 Doctrine,这可以使用

$name = Doctrine::getTable('nametable')
  ->createQuery()
  ->select('name')
  ->orderBy('RAND()')
  ->fetchOne();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM