GroupBy and date

75 views Asked by At

I'm trying to get for each day, the amount of reservations. I have done this doctrine request :

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

I get a result like that (from my webservice)

 {
      "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"
    }

The problem is that sometimes the dates are not grouped correctly. For exemple, the 2016-12-22 is split in 2. Same for 24, 26.

How can I do ?

1

There are 1 answers

0
rokas On BEST ANSWER

Looks like you have datetime field in your database. The solution would be group by date format:

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

But DATE_FORMAT isnt implemented in default doctrine bundle, so you will have to add beberlei/DoctrineExtensions and then add the respective function to your doctrine bundle config like:

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