我正在为一个可能会获得大量流量的项目使用Doctrine2,我很乐意在搜索页面中进行分页,并且每页只获取5个结果那么,在不需要使用条令扩展和保留ORM抽象层的情况下,有没有一种好的方法可以做到这一点呢?我的意思是,我不想写任何形式的dql查询,并将我的代码保持为以下格式:
$repo= $this->getDoctrine()
->getEntityManager()
->getRepository('AcmeOfficeBundle:Project');
$list=$repo->findBy(array('PROJ_private' => "0"));
条令2.2配备了分页器。但是,确实需要编写DQL查询。
如果你坚持不写任何DQL,你可以从Doctrine EntityRepository类开始;特别是findBy()方法。它有限制和偏移的可选参数,所以你可以尝试这样的方法(使用你的例子作为基线):
$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
);
在条令ORM 2.3中,您还可以在实体存储库中使用Criteria
和matching
。它现在(从2.5开始)适用于nToMany关系。
当您的查询需要除equals之外的另一个比较时,或者当对另一个实体的OneToMany集合进行分页时,这会有所帮助。
$page = (isset($_GET['page']) && $_GET['page'] > 0 ? $_GET['page'] : 1);
$limit = 20;
$offset = ($limit * ($page - 1));
$criteria = DoctrineCommonCollectionsCriteria::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-集合
避免写入DQL的一个好选择是使用Pagerfanta 对集合进行操作
https://github.com/whiteoctober/Pagerfanta
use PagerfantaAdapterDoctrineCollectionAdapter;
$user = $em->find("AppDoctrineORMUser", 1);
$adapter = new DoctrineCollectionAdapter($user->getGroups());