How to select randomly with doctrine

前端 未结 13 1044
耶瑟儿~
耶瑟儿~ 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:40

    @Krzysztof's solution is IMHO best here, but RAND() is very slow on large queries, so i updated @Krysztof's solution to gives less "random" results, but they are still random enough. Inspired by this answer https://stackoverflow.com/a/4329492/839434.

    namespace Project\ProductsBundle\Entity;
    
    use Doctrine\ORM;
    
    class ProductRepository extends ORM\EntityRepository
    {
        /**
         * @param int $amount
         * @return Product[]
         */
        public function getRandomProducts($amount = 7)
        {
            return $this->getRandomProductsNativeQuery($amount)->getResult();
        }
    
        /**
         * @param int $amount
         * @return ORM\NativeQuery
         */
        public function getRandomProductsNativeQuery($amount = 7)
        {
            # set entity name
            $table = $this->getClassMetadata()
                ->getTableName();
    
            # create rsm object
            $rsm = new ORM\Query\ResultSetMapping();
            $rsm->addEntityResult($this->getEntityName(), 'p');
            $rsm->addFieldResult('p', 'id', 'id');
    
            # sql query
            $sql = "
                SELECT * FROM {$table}
                WHERE id >= FLOOR(1 + RAND()*(
                    SELECT MAX(id) FROM {$table})
                ) 
                LIMIT ?
            ";
    
            # make query
            return $this->getEntityManager()
                ->createNativeQuery($sql, $rsm)
                ->setParameter(1, $amount);
        }
    }
    

提交回复
热议问题