1

我有以下查询,如何在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 的排序

如果有人可以帮助我,那就太好了,因为这已经把我的头发拉了几天了。

4

1 回答 1

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();
于 2012-10-16T10:50:30.107 回答