2014-04-16 28 views
1

我一直堅持這個約10小時從SQL中使用RAND()函數Doctrine2

我需要使用此查詢(ORDER的優化版本BY RAND)

public function findAllRandom() 
{ 
    return $this->getEntityManager() 
    ->createQuery(
     'SELECT p FROM GabrielUploadBundle:Image p WHERE RAND() < 0.0001 ORDER BY RAND() LIMIT 20') 
    ->getResult(); 
} 

而且當然,因爲我使用DQL我需要實現RAND()函數

<?php 
namespace Gabriel\UploadBundle\DoctrineFunctions; 
use Doctrine\ORM\Query\Lexer; 

/** 
* RandFunction ::= "RAND" "(" ")" 
*/ 
class Rand extends \Doctrine\ORM\Query\AST\Functions\FunctionNode 
{ 
    public function parse(\Doctrine\ORM\Query\Parser $parser) 
    { 
     $parser->match(Lexer::T_IDENTIFIER); 
     $parser->match(Lexer::T_OPEN_PARENTHESIS); 
     $parser->match(Lexer::T_CLOSE_PARENTHESIS); 
    } 

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) 
    { 
     return 'RAND()'; 
    } 
} 

//Config.yml

orm: 
(...) 
    dql: 
     numeric_functions: 
     Rand: Gabriel\UploadBundle\DoctrineFunctions\Rand 

問題是我不斷收到此錯誤:

[Syntax Error] line 0, col 77: Error: Expected end of string, got '(' 

的RAND()的源代碼的來源:

https://gist.github.com/Ocramius/919465

如何從配置增加:

http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html

有關向DQL添加功能的演示

http://punkave.com/window/2012/07/24/for-the-php-crowd-adding-custom-functions-to-doctrine-2-dql

編輯: 經過進一步的研究,我發現,爲了通過功能不支持DQL: 來源: http://docs.doctrine-project.org/en/2.1/reference/faq.html#can-i-sort-by-a-function-for-example-order-by-rand-in-dql

若要解決此隱藏的值可以被添加

public function findAllRandom() 
{ 
    return $this->getEntityManager() 
    ->createQuery(
     'SELECT p,RAND() AS HIDDEN rand FROM GabrielUploadBundle:Image p ORDER BY rand') 
    ->getResult(); 
} 

但由於某些原因,它不適用於WHERE子句

public function findAllRandom() 
{ 
    return $this->getEntityManager() 
    ->createQuery(
     'SELECT p,RAND() AS HIDDEN rand FROM GabrielUploadBundle:Image p WHERE rand < 0.00001 ORDER BY rand') 
    ->getResult(); 
} 

where子句的解決方案是讚賞,大家都知道,使用ORDER BY RAND()函數可以減緩服務器(在我們的例子中甚至崩潰吧)

回答