2012-03-06 56 views
11

我正在使用Doctrine2進行一個項目,該項目可能會獲得大量流量,並且我正在搜索頁面中進行一些分頁,並且每頁只獲取5個結果 那麼有沒有一種好的方法可以做到這一點,而不需要使用doctrine擴展並保留ORM抽象層呢?我的意思是我不想寫任何形式的DQL的查詢,並保持我的代碼格式如下:在Doctrine2/Symfony2中使用沒有Doctrine分頁符擴展的分頁

$repo= $this->getDoctrine() 
        ->getEntityManager() 
        ->getRepository('AcmeOfficeBundle:Project'); 
     $list=$repo->findBy(array('PROJ_private' => "0")); 

回答

35

學說2.2 ships with a paginator。但是,確實要求您編寫DQL查詢。

如果你堅持不寫任何DQL,你可以先看看Doctrine EntityRepository類;具體而言,the findBy() method。它有限制的自選參數和偏移,這樣你就可以(使用你的例子爲基準)嘗試這樣:

$num_pages = x; // some calculation of what page you're currently on 
$repo = $this->getDoctrine() 
       ->getRepository('AcmeOfficeBundle:Project'); 
$list = $repo->findBy(
    array('PROJ_private' => "0"), //search criteria, as usual 
    array(/* orderBy criteria if needed, else empty array */), 
    5, // limit 
    5 * ($num_pages - 1) // offset 
); 
+1

THX對教義2.2運輸與分頁程序的一部分,不知道。 – Matt 2012-03-06 17:12:18

+2

如何獲得結果集的總頁數?我是否需要運行一個單獨的findBy()而沒有最後兩個參數來獲取結果的總數然後自己計算它?這似乎效率低下,但我不確定是否有更優雅的方式來做到這一點。 – imkingdavid 2014-05-20 15:52:45

0

避免寫DQL是使用Pagerfanta

集合進行操作一個很好的選擇https://github.com/whiteoctober/Pagerfanta

use Pagerfanta\Adapter\DoctrineCollectionAdapter; 
$user = $em->find("App\DoctrineORM\User", 1); 
$adapter = new DoctrineCollectionAdapter($user->getGroups()); 
0

教義ORM 2.3,你還可以利用與matching對實體倉庫一起Criteria。現在(2.5版本)適用於nToMany關係。

這有助於您的查詢需要除等號之外的其他比較或分頁另一個實體的OneToMany集合時。

$page = (isset($_GET['page']) && $_GET['page'] > 0 ? $_GET['page'] : 1); 
$limit = 20; 
$offset = ($limit * ($page - 1)); 
$criteria = \Doctrine\Common\Collections\Criteria::create() 
    ->setMaxResults($limit) 
    ->setFirstResult($offset); 
$expr = $criteria->expr(); 
$user = $em->getRepository('AcmeOfficeBundle:Project') 
    ->matching($criteria->where($expr->gt('PROJ_private', 0))); 
$total_records = $user->count(); 

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html#filtering-collections