How to select randomly with doctrine

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

    Why not to use repository?

    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');
    
            # make query
            return $this->getEntityManager()->createNativeQuery("
                SELECT p.id FROM {$table} p ORDER BY RAND() LIMIT 0, {$amount}
            ", $rsm);
        }
    }
    

提交回复
热议问题