【问题标题】:Symfony / Doctrine COUNT Group By and Left JOINSymfony / Doctrine COUNT Group By and Left JOIN
【发布时间】:2016-05-27 14:17:18
【问题描述】:

我在 symfony 中有两个表,通过 ManyToOne 双向关系连接。文章和日期。

我想对同一个 a.id 的所有 d.quantity 求和,我该怎么做?

我试试:

在我的表(日期)中,我有:

+----------------------------
| id   | a.id  |   quantity
+----------------------------
| 1    | 4     |      1 
| 2    | 4     |      3
| 3    | 6     |      4
| 4    | 5     |      6
| 5    | 4     |      15 
----------------------------

$allIndispo = $qb
    ->select('a2.id')
    ->leftJoin('a2.dates', 'd')
    ->where('(a2.quantity - COUNT(d.quantity)) <= 0')
    ->groupBy('d.quantity')
    ->orderBy('a2.id', 'ASC');

【问题讨论】:

  • 你不想按a.id和SUM数量分组吗?
  • 是的,但是当我通过 a2.id 更改组时,我得到:SQLSTATE[HY000]:一般错误:1111 Invalid use dof GROUP
  • 这可能与您的 WHERE 子句而不是 GROUP BY 子句有关。 stackoverflow.com/questions/2330840/… 可能是相关的。

标签: php symfony doctrine-orm


【解决方案1】:

您可能需要使用 HAVING 而不是 WHERE,并按 a.id 分组,而不是数量,并投影(在选择中)结果。

$allIndispo = $qb
    ->select('a2.id, SUM(a2.quantity) as total')
    ->leftJoin('a2.dates', 'd')
    ->groupBy('a2.id')
    ->having('(a2.quantity - COUNT(d.quantity)) <= 0')
    ->orderBy('a2.id', 'ASC');

【讨论】:

    【解决方案2】:

    你应该阅读this

        $repository = $this->getDoctrine()
        ->getRepository('AppBundle:Product');
    
    // createQueryBuilder automatically selects FROM AppBundle:Product
    // and aliases it to "p"
    $query = $repository->createQueryBuilder('p')
        ->where('p.price > :price')
        ->setParameter('price', '19.99')
        ->orderBy('p.price', 'ASC')
        ->getQuery();
    
    $products = $query->getResult();
    // to get just one result:
    // $product = $query->setMaxResults(1)->getOneOrNullResult();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多