GroupBy和日期

时间:2016-12-30 08:03:23

标签: mysql symfony doctrine doctrine-query

我试图获取每一天的预订金额。我已经完成了这个学说要求:

   // prepare date for request
    $today = new DateTime('now');
    $lastMonth = new DateTime('-30 days');

    $qb
        ->select('r.reservationDate, sum(r.totalAmountNoTaxes) as totalAmountNoTaxes')
        ->where('r.companyId = :companyId')
        ->setParameter('companyId', $companyId)
        ->andWhere('r.reservationDate BETWEEN :month AND :today')
        ->setParameter('month', $lastMonth->format('Y-m-d'))
        ->setParameter('today', $today->format('Y-m-d'))
        ->orderBy('r.reservationDate', 'ASC')
        ->groupBy('r.reservationDate')
    ;

我得到的结果(来自我的网络服务)

 {
      "reservationDate": "2016-12-21T07:41:12+0000",
      "totalAmountNoTaxes": "26150.30"
    },
    {
      "reservationDate": "2016-12-22T07:41:01+0000",
      "totalAmountNoTaxes": "230.00"
    },
    {
      "reservationDate": "2016-12-22T07:41:02+0000",
      "totalAmountNoTaxes": "21966.40"
    },
    {
      "reservationDate": "2016-12-23T07:40:52+0000",
      "totalAmountNoTaxes": "20407.05"
    },
    {
      "reservationDate": "2016-12-24T07:40:41+0000",
      "totalAmountNoTaxes": "4319.75"
    },
    {
      "reservationDate": "2016-12-24T07:40:42+0000",
      "totalAmountNoTaxes": "7261.20"
    },
    {
      "reservationDate": "2016-12-25T07:40:28+0000",
      "totalAmountNoTaxes": "14821.45"
    },
    {
      "reservationDate": "2016-12-26T07:40:16+0000",
      "totalAmountNoTaxes": "494.50"
    },
    {
      "reservationDate": "2016-12-26T07:40:17+0000",
      "totalAmountNoTaxes": "14541.25"
    },
    {
      "reservationDate": "2016-12-27T07:06:40+0000",
      "totalAmountNoTaxes": "25763.90"
    },
    {
      "reservationDate": "2016-12-28T05:37:43+0000",
      "totalAmountNoTaxes": "20595.70"
    }

问题是有时候日期没有正确分组。例如,2016-12-22分为2.相同的24,26。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您的数据库中似乎有datetime字段。 解决方案是按日期格式:

//
->groupBy('DATE_FORMAT(r.reservationDate, '%Y%m%d')')
//

但是DATE_FORMAT并没有在默认的doctrine包中实现,所以你必须添加beberlei/DoctrineExtensions然后将相应的函数添加到你的教条包配置中,如:

doctrine:
    dbal:
        ....
    orm:
        ....
        dql:
            string_functions:
                DATE_FORMAT: DoctrineExtensions\Query\Mysql\DateFormat