How to select randomly with doctrine

前端 未结 13 1045
耶瑟儿~
耶瑟儿~ 2020-11-27 20:21

Here is how I query my database for some words

$query = $qb->select(\'w\')
    ->from(\'DbEntities\\Entity\\Word\', \'w\')
    ->where(\'w.indiction         


        
13条回答
  •  旧时难觅i
    2020-11-27 20:51

    Probably the easiest (but not necessarily the smartest) way to get a single object result ASAP would be implementing this in your Repository class:

    public function findOneRandom()
    {
        $className = $this->getClassMetadata()->getName();
    
        $counter = (int) $this->getEntityManager()->createQuery("SELECT COUNT(c) FROM {$className} c")->getSingleScalarResult();
    
        return $this->getEntityManager()
    
            ->createQuery("SELECT ent FROM {$className} ent ORDER BY ent.id ASC")
            ->setMaxResults(1)
            ->setFirstResult(mt_rand(0, $counter - 1))
            ->getSingleResult()
        ;
    }
    

提交回复
热议问题