How to select randomly with doctrine

前端 未结 13 1043
耶瑟儿~
耶瑟儿~ 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条回答
  •  时光说笑
    2020-11-27 20:49

    I know this is an old question. But I used the following solution to get the random row.

    Using an EntityRepository method:

    public function findOneRandom()
    {
        $id_limits = $this->createQueryBuilder('entity')
            ->select('MIN(entity.id)', 'MAX(entity.id)')
            ->getQuery()
            ->getOneOrNullResult();
        $random_possible_id = rand($id_limits[1], $id_limits[2]);
    
        return $this->createQueryBuilder('entity')
            ->where('entity.id >= :random_id')
            ->setParameter('random_id', $random_possible_id)
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
    

提交回复
热议问题