隨機記錄下將返回一個隨機記錄與學說:從數據庫中獲得/實體使用CI2 + Doctrine2
$name = Doctrine::getTable('nametable')
->createQuery()
->select('name')
->orderBy('RAND()')
->fetchOne();
但我跑CI2 + Doctrine2,所以它不工作Call to undefined method Doctrine::getTable()
我已經試過
$data = $this->doctrine->em->getRepository('ORM\Project\Names')
->orderBy('RAND()')
->fetchOne();
但是,這並不工作之一:Uncaught exception 'BadMethodCallException' with message 'Undefined method 'orderBy'. The method name must start with either findBy or findOneBy!'
也許findOneBy是我想要的,但它期望一個數組。
有獲取在此設置一個隨機記錄一個優雅的方式?
編輯:
這是我想出來的:
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Femalenames u");
$result = $query->getSingleResult();
$highval = $result[1];
$random_name = rand(1,$highval);
$name = $this->doctrine->em->find('ORM\Dynasties2\Femalenames', $random_name);
$mother_name = $name->getName();
當然還有一個更清潔的方式???很顯然,在CI2/Doctrine2中沒有像RAND()這樣的東西,只是寫了一個SQL查詢。
是的,這就是處理它的教義方式。你也可以使用這樣的功能:https://gist.github.com/Thinkscape/124d658e4076421c0516 – 2014-07-26 13:43:49