问题描述
我正在研究Symfony2项目,所以我决定使用KNPPaginatorBundle构建一个简单的分页系统.因此,我创建了一个Product实体,并希望将分页器添加到indexAction操作(由CRUD命令生成)中.
I'm working on a Symfony2 project and I decided to use KNPPaginatorBundle to build an easy pagination system. So I created a Product entity and I want to add the paginator to indexAction action (generated by CRUD command).
// Retrieving products.
$em = $this->getDoctrine()->getManager();
//$entities = $em->getRepository('LiveDataShopBundle:Product')->findAll();
$dql = "SELECT a FROM LiveDataShopBundle:Product a";
$entities = $em->createQuery($dql);
// Creating pagnination
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$entities,
$this->get('request')->query->get('page', 1),
20
);
它工作正常,但我想使用产品的存储库,而不是直接在控制器中创建查询.我怎样才能做到这一点 ?实际上,直接将结果集合添加到分页对象太慢了,因为它加载了所有乘积,然后分页了ArrayCollection.
It works fine but I want to use the Product's repository instead of creating the query directly in the controller. How can I do that ?In fact, directly add the collection of results to the paginate object is just too slow because its load all products then paginate the ArrayCollection.
谢谢.
K4
推荐答案
我建议在您的ProductRepository
中使用QueryBuilder
,然后将其传递给分页器:
I suggest using QueryBuilder
in your ProductRepository
and then passing that to the paginator:
ProductRepository extends EntityRepository
{
// This will return a QueryBuilder instance
public function findAll()
{
return $this->createQueryBuilder("p");
}
}
在控制器中:
$products = $productRepository->findAll();
// Creating pagnination
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$products,
$this->get('request')->query->get('page', 1),
20
);
这篇关于如何使用KNPPaginatorBundle使用Doctrine存储库对结果进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!