2016-12-27 63 views

回答

1

我已經解決了我的問題是這樣的:

public function getRandomUser() 
{ 
    $qb = $this->getDocumentManager()->createQueryBuilder('AppBundle:User'); 
    $count = $qb->getQuery()->count(); 
    $skip_count = random_int(0, $count); 
    $qb->skip($skip_count); 

    return $qb->getQuery()->getSingleResult(); 
} 
2
<?php 

// Create Query Builder. 
$dm = $this->getDocumentManager()->createQueryBuilder('Document'); 

// Count documents. 
$count = $dm->getQuery()->execute()->count(); 

// Get random number not exceeding $count variable. 
$random = mt_rand(0, $count); 

// Query for document with skip. 
$random_document = $dm->skip($random) 
         ->getQuery() 
         ->getSingleResult(); 
1

嘗試這種解決方案:

public function getRandomDocument() 
{ 
    $qb = $this->getDocumentManager()->createQueryBuilder('YourBundle:TargetDocument'); 
    $count = $qb->getQuery()->count(); 
    $skip_count = random_int(0, $count); 
    $qb->skip($skip_count); 

    return $qb->getQuery()->getSingleResult(); 
}