如何使用KNPPaginatorBundle使用Doctrine存储库对结果进行分页?

编程入门 行业动态 更新时间:2024-10-25 14:34:13
本文介绍了如何使用KNPPaginatorBundle使用Doctrine存储库对结果进行分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在研究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存储库对结果进行分页?

本文发布于:2023-06-13 09:34:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/678987.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分页   如何使用   KNPPaginatorBundle   Doctrine

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!