我将Symfony2与Doctrine ORM和Twig一起用于视图部分。
实际上我写了一个类到静态调用学说分页这样:
use Doctrine\ORM\Tools\Pagination\Paginator;
class DoctrineHelp
{
static public function paginate(Query $query, &$pageSize = 10, &$currentPage = 1){
$pageSize = (int)$pageSize;
$currentPage = (int)$currentPage;
if( $pageSize < 1 ){
$pageSize = 10;
}
if( $currentPage < 1 ){
$currentPage = 1;
}
$paginator = new Paginator($query);
$paginator
->getQuery()
->setFirstResult($pageSize * ($currentPage - 1))
->setMaxResults($pageSize)
;
return $paginator;
}
}
在控制器中(控制器中的简单Sf2 indexAction)创建请求,调用它们并为视图部分设置全部:
$page = 1;
$pageSize = 5;
$articlesQuery = $em->getRepository('MyOwnBundle:Article')->getBlogArticles($languageId);
$ArticlesPaginator = DoctrineHelp::paginate($articlesQuery, $pageSize, $page);
return array('Articles' => $ArticlesPaginator);
getBlogArticles()方法:
public function getBlogArticles($languageId){
$qb = $this->createQueryBuilder(self::ALIAS_NAME);
$qb->andWhere(self::ALIAS_NAME . '.language = :languageId')->setParameter('languageId', $languageId);
$qb->andWhere(self::ALIAS_NAME . ".disabled_at IS NULL");
$qb->addOrderBy(self::ALIAS_NAME . '.published_at', 'DESC');
$qb->addOrderBy(self::ALIAS_NAME . '.id', 'DESC');
return $qb->getQuery();
}
现在当我显示时,我有意想不到的结果,我在Twig部分尝试的代码:
{{ dump(Articles|length) }} {# here "int 23" for example in this case because result without limit is 23, ok I understand #}
{% for anArticle in Articles %}
{{ dump(loop.first) }} {# as expected here "true" for the first and false for other #}
{{ dump(loop.last) }} {# always "false" even for the fifth result who is suppose to be "true" #}
{{ dump(loop.length) }} {# here return always "int 23" in spite expected 5 #}
{% endfor %}
{# for display my 5 object in spite loop.last and loot.length not expected result #}
我向Sf2团队发出问题:https://github.com/symfony/symfony/issues/11316 和Doctrine ORM团队:http://www.doctrine-project.org/jira/browse/DDC-3207 但两个团队都假设没有问题。
现在我的问题是,如果{{loop.last}}和{{loop.length}}没有提供正确的结果,我想如何使用该对象? (实际上我使用{{loop.first}}的技巧尽管当前的页码(这对我来说至少是预期的结果)提供了正确的结果) 如果两个团队都认为没有问题,怎么可能纠正这个?
先谢谢你。
答案 0 :(得分:2)
最后解决方案是循环迭代器,这意味着:
{% for anArticle in Articles.iterator %}
在这种情况下,所有转储内部添加预期结果:)