K4t*_*ini 10 php pagination symfony knppaginator knppaginatorbundle
我正在研究一个Symfony2项目,我决定使用KNPPaginatorBundle构建一个简单的分页系统.所以我创建了一个Product实体,我想将paginator添加到indexAction动作(由CRUD命令生成).
// 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
);
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我想使用产品的存储库,而不是直接在控制器中创建查询.我怎样才能做到这一点 ?实际上,直接将结果集合添加到paginate对象的速度太慢,因为它加载所有产品然后对ArrayCollection进行分页.
提前致谢.
K4
Alb*_*dez 17
我建议QueryBuilder在你的使用中ProductRepository然后将它传递给paginator:
ProductRepository extends EntityRepository
{
// This will return a QueryBuilder instance
public function findAll()
{
return $this->createQueryBuilder("p");
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中:
$products = $productRepository->findAll();
// Creating pagnination
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$products,
$this->get('request')->query->get('page', 1),
20
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14545 次 |
| 最近记录: |