Symfony2 原则错误:无法对使用 HAVING 子句的查询进行计数。使用输出步行器进行分页

问题描述 投票:0回答:4

我正在尝试获取非空集合,即至少有 1 个对象。集合实体与对象实体具有一对多关系。我正在使用 KNP 分页器对结果进行分页。这是我的职能:

  public function fetchAction(Request $request){
    $em = $this->getDoctrine()->getManager();

    $page = $request->get('page', 1);
    $limit = 10;

    $collections = $em->createQueryBuilder()
        ->select('c')
        ->add('from', 'CollectionBundle:Collection c LEFT JOIN c.object o')
        ->having('COUNT(o.id)>0')
        ->orderBy('c.date', 'DESC')
        ->getQuery();

    $collections = $this->get("knp_paginator")->paginate($collections, $page, $limit);

    return $this->render('CollectionBundle:Collection:fetch.html.twig', [
        'collections' => $collections
    ]);
}

错误

我不断收到以下错误

 Cannot count query that uses a HAVING clause. Use the output walkers for pagination

没有“Having”子句一切正常,但我必须获得非空集合。

mysql symfony doctrine-orm knppaginator
4个回答
17
投票

wrap-queries 解决了这个问题

 $collections = $this->get("knp_paginator")->paginate($collections, $page, $limit,array('wrap-queries'=>true));

2
投票

您可以实施手动计数,如文档中此处所述。

例如,您可以按如下方式修改代码:

$count = $em->createQueryBuilder() ->select('COUNT(c)') ->add('from', 'CollectionBundle:Collection c LEFT JOIN c.object o') ->having('COUNT(o.id)>0') ->orderBy('c.date', 'DESC') getSingleScalarResult(); $collections = $em->createQueryBuilder() ->select('c') ->add('from', 'CollectionBundle:Collection c LEFT JOIN c.object o') ->having('COUNT(o.id)>0') ->orderBy('c.date', 'DESC') ->getQuery(); $collections->setHint('knp_paginator.count', $count); $collections = $this->get("knp_paginator")->paginate($collections, $page, $limit,array('distinct' => false)); return $this->render('CollectionBundle:Collection:fetch.html.twig', [ 'collections' => $collections ]);
希望这有帮助


1
投票
我的解决方案基于@Matteo的解决方案,因为我的查询有点复杂,我也想分享我的版本:

$qb = $this->createQueryBuilder('c'); $qb->select('count(c.id)') ->addSelect('COUNT(DISTINCT m.id) AS HIDDEN messageCount') ->addSelect('COUNT(DISTINCT f.id) AS HIDDEN fileCount') ->join('c.user', 'u') ->join('c.status', 's') ->join('c.company', 'comp') ->leftJoin('c.files', 'f') ->leftJoin('c.messages', 'm'); $this->_set_filters($filter, $qb); $qb->groupBy('c.id'); $countQuery = $qb->getQuery(); /** wrap query with SELECT COUNT(*) FROM ($sql) * I don't know what exactly does this block but * I coppied it from Doctrine\ORM\Tools\Pagination\Paginator::getCountQuery() */ $platform = $this->getEntityManager()->getConnection()->getDatabasePlatform(); $rsm = new Query\ResultSetMapping(); $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count'); $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $countQuery->setResultSetMapping($rsm); return $countQuery->getSingleScalarResult(); //returns integer
    

0
投票
对于那些登陆此页面并询问在哪里可以找到选项的人,您可以在此处查看基本组件文档:

https://github.com/KnpLabs/knp-components/blob/master/docs/pager/config。 md

© www.soinside.com 2019 - 2024. All rights reserved.