2013-07-04 18 views
0

我一直在試圖拉出一個隨機行的錯誤,我已經使用這個:選擇在Symfony2中隨機DB入門 - 獲取

這是示例代碼,我發現它並沒有真正幫助(我發現這裏: https://gist.github.com/pierroweb/1518601

class QuestionRepository extends EntityRepository 
{ 
    public function findOneRandom() 
    { 
     $em = $this->getEntityManager(); 
     $max = $em->createQuery(' 
      SELECT MAX(q.id) FROM EnzimQuestionBundle:Question q 
      ') 
      ->getSingleScalarResult(); 
     return $em->createQuery(' 
      SELECT q FROM EnzimQuestionBundle:Question q 
      WHERE q.id >= :rand 
      ORDER BY q.id ASC 
      ') 
      ->setParameter('rand',rand(0,$max)) 
      ->setMaxResults(1) 
      ->getSingleResult(); 
    } 
} 

現在我有這樣的事情:

$em = $this->getEntityManager(); 
    $max = $em->createQuery('SELECT MAX(p.id) FROM GreenMonkeyDevGlassShopBundle:Product p')->getSingleScalarResult(); 
    return $em->createQuery('SELECT p FROM GreenMonkeyDevGlassShopBundle:Product p INNER JOIN (SELECT p2.categories. FROM GreenMonkeyDevGlassShopBundle:Product p.categories WHERE :cid IN(pc) p.id >= :rand ORDER BY p.id ASC') 
     ->setParameter('cid', $category_id) 
     ->setParameter('rand',rand(0,$max)) 
     ->setMaxResults(intval($limit)) 
     ->getSingleResult(); 

雖然我不斷收到此錯誤: FatalErrorException: Error: Call to undefined method Doctrine\ORM\Query\ResultSetMapping::addRootEntityFromClassMetadata() in /var/www/gmd-milkywayglass/src/GreenMonkeyDev/GlassShopBundle/Entity/CategoryRepository.php line 42

有關我可以做錯什麼的想法?我知道教義沒有一個隨機獲取方法。也許有一些簡單的解決方案?謝謝!

回答

1

你應該嘗試寫自己的DQL功能,才能在查詢中使用RAND():

namespace My\Custom\Doctrine2\Function; 

/** 
* RandFunction ::= "RAND" "(" ")" 
*/ 
class Rand extends 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()'; 
    } 
} 

後,你必須註冊在Symfony2的config.yml此DQL功能

doctrine: 
    dbal: 
     # ... 
    orm: 
     #... 
     dql: 
      numeric_functions: 
       RAND: My\Custom\Doctrine2\Function 

對於更多的信息,請閱讀以下鏈接

DQL User Defined Functions

How to Register Custom DQL Functions in Symfony2

+0

真的希望我不會這樣做。謝謝! – TooTiredToDrink