【问题标题】:Querying and returning distinct values & sum of quantities查询和返回不同的值和数量的总和
【发布时间】:2014-04-14 20:38:20
【问题描述】:

我在 Symfony 2 中有一个查询,我试图从带有连接的表中返回唯一值以及这些唯一值的总和。

例如:

Inventory Table: 

id | product_id | qty  | warehouse_id
----------------------------------------
1  | 123        | 5    | 1
2  | 123        | 5    | 1
3  | 123        | 5    | 1
4  | 234        | 5    | 1 
5  | 345        | 5    | 1
6  | 345        | 5    | 1
7  | 345        | 5    | 1  
8  | 345        | 5    | 1  
9  | 345        | 5    | 1  
10 | 345        | 5    | 1  

Product Table: 

id   | name       | sku        | description    |
------------------------------------------------
123  | Test 123   | Test 123   | Test 123
234  | Test 234   | Test 234   | Test 234
345  | Test 345   | Test 345   | Test 345

所以最后,我在数组中需要的几乎是以下信息以及从连接中返回的信息:

product_id: 123   qty: 15
product_id: 234   qty: 5
product_id: 345   qty: 30

这是我的完整查询...我只是不太确定如何在 Symfony 2 中使用该学说执行此操作。感谢您的帮助!

$search_string = trim($search_string);
$em = $this->getEntityManager();
$query = $em->createQuery("
    SELECT    i, p, il, w
    FROM      WIC\InventoryBundle\Entity\Inventory i
    LEFT JOIN i.product p
    LEFT JOIN i.inventoryLocation il
    LEFT JOIN il.warehouse w
    WHERE     (p.name LIKE :tag OR p.sku LIKE :tag OR p.description LIKE :tag)
    AND       p.account = :account_id
    AND       il.warehouse = :location_id");
$query->setParameters(array(
    'tag'           => "%$search_string%",
    'account_id'    => $account_id,
    'location_id'    => $location_id
));
return $query->getArrayResult();

【问题讨论】:

    标签: php mysql sql symfony doctrine-orm


    【解决方案1】:

    你可以试试

    $search_string = trim($search_string);
    $q = $this->getEntityManager()
              ->getRepository('YourBundle:Inventory')
              ->createQueryBuilder('i');
    $query = $q->select('SUM(DISTINCT(i.qty))')
        ->leftJoin('i.product', 'p')
        ->leftJoin('i.inventoryLocation', 'il')
        ->where($q->exp()->like('p.name', ':tag')
        ->orWhere($q->exp()->like('p.sku', ':tag')
        ->orWhere($q->exp()->like('p.description', ':tag')
        ->andWhere('p.account = :account_id')
        ->andWhere('il.warehouse = :location_id')
        ->setParameter('tag', $q->expr()->literal("%$search_string%"))
        ->setParameter('account_id', $account_id)
        ->setParameter('location_id', $location_id)
        ->getQuery();
    
    return $query->getResult();
    

    根据您在实体映射中的实际情况,我并没有准确地说明您的实体字段名称是什么,因此它们是正确的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多