在Symfony2中选择随机数据库条目 - 获取错误

时间:2013-07-04 06:22:38

标签: php symfony doctrine dql

我一直想要随机抽出一行,我用过这个:

这是我发现的示例代码,它没有真正帮助(我在这里找到: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

对我可能做错的任何想法?我知道Doctrine没有随机方法。也许有一些简单的解决方案?谢谢!

1 个答案:

答案 0 :(得分: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