在Symfony2中向paginator(KNP Paginator)添加自定义查询?

时间:2012-10-16 10:27:02

标签: php symfony pagination

我有以下查询,如何在 Symfony2

中编写这些查询
SELECT Inventory_Stock.id, Inventory_Stock.quantity, SUM(InventoryUsage.quantity)
       ,Inventory_Stock.quantity - SUM(InventoryUsage.quantity) AS Stock 

FROM Inventory_Stock LEFT JOIN InventoryUsage ON Inventory_Stock.id = InventoryUsage.InventoryStock_id 

WHERE Inventory_Stock.id = 26 OR
      Inventory_Stock.id = 27

GROUP BY Inventory_Stock.id 
ORDER BY Stock DESC

我需要以symfony的方式实现上述查询

 private function getList($query = null)
{
    $em = $this->getDoctrine()->getEntityManager();

    if(!$query)
    {
        $query = $em->createQueryBuilder()
            ->select('i')
            ->from('ItxBundle:InventoryStock', 'i')
            ->innerJoin('i.Product','p')
            ->getQuery();

    }
    $adapter = $this->get('knp_paginator.adapter');
    $adapter->setQuery($query);
    $adapter->setDistinct(TRUE);


    $paginator = new Paginator($adapter);
    $paginator->setCurrentPageNumber($this->get('request')->query->get('page', 1));
    $paginator->setItemCountPerPage($this->container->parameters['items_per_page']);
    $paginator->setPageRange($this->container->parameters['page_range']);
    return $paginator;
}

并在视图中

{% if entity.quantity - entity.Usage < 0 %}
    0
{% else %}
    {{ entity.quantity - entity.Usage | number_format(0) }}
{% endif %}

我在这里使用三个表,下面给出了关系

InventoryStock 1 - n InventoryUsage InventoryStock 1 - 1产品

需要显示可用库存(InventoryStock.Quanitity - sum(InventoryUsage.quanitity))

还需要实现基于Stock的排序

如果有人可以帮我解决这个问题会很好,因为这已经把我的头发拉了几天。

1 个答案:

答案 0 :(得分:1)

我建议使用WhiteOctoberPagerfantaBundle捆绑包。它允许您像往常一样创建自己的Query对象,然后将其传递给相关的Pagerfanta适配器。看起来好像你正在使用Doctrine,例如......

    // at the top of the file:
    use Pagerfanta\Pagerfanta, 
        Pagerfanta\Adapter\DoctrineORMAdapter;


    // Build your query...
    /** @var $query \Doctrine\ORM\Query */
    //$query = ... 

    $currentPage = $this->getRequest()->get('page', 1);

    $pagerfanta = new Pagerfanta(new DoctrineORMAdapter($query));
    $pagerfanta
        ->setMaxPerPage($maxItems) // you'll need to specify this value
        ->setCurrentPage($currentPage)
    ;
    $results = $pagerfanta->getCurrentPageResults();