简体   繁体   English

Symfony /教义COUNT分组者和左加入者

[英]Symfony / Doctrine COUNT Group By and Left JOIN

I have two Tables in symfony join by ManyToOne bidirectional relationship. 我通过ManyToOne双向关系在symfony中加入了两个表。 articles and dates. 文章和日期。

I would like to sum all the d.quantity for the same a.id How can I do that ? 我想对同一个a.id的所有d.quantity求和,我该怎么做?

I try : 我尝试:

In my table (dates) i have : 在我的表(日期)中,我有:

+----------------------------
| 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');

You probably need to use HAVING instead of WHERE, and group by the a.id, not for quantity, and project (in the select) the result. 您可能需要使用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');

You should read 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM