如何使用 Symfony 的查询生成器制作日期范围计数器并用零填充空白

How to use the query builder of Symfony to make a date range counter and fill the gaps with zeros

我有一个查询,通过按注册日期对用户进行分组来计算用户数量。

return $this->createQueryBuilder('s')
->select(' date(s.created_at) as x, count(1) as y')
->where("s.created_at between datesub(now(), :months, 'Month') and now()")
->setParameter('months', $months)
->groupBy('x')
->orderBy('x')
->getQuery()
->getResult();

但他们目前在我的数据集中存在差距。

所以我有 sql 请求来填补空白,但我不知道如何使用 Symfony 的查询生成器创建复杂的请求。

SELECT ranger.ranger_date AS x, COALESCE(counter.counter_value, 0) as y
FROM (
    SELECT DATE(s.created_at) AS counter_date, count(*) AS counter_value
    FROM statistic AS s
    WHERE s.created_at between DATE_SUB(NOW(), INTERVAL 3 MONTH) and now()
    GROUP BY counter_date
) AS counter
RIGHT JOIN (
    SELECT DATE(DATE_SUB(NOW(), INTERVAL units.i + tens.i * 10 + hundreds.i * 100 DAY)) AS ranger_date
    FROM (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)units
    CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)tens
    CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)hundreds
    WHERE DATE_SUB(NOW(), INTERVAL units.i + tens.i * 10 + hundreds.i * 100 DAY) BETWEEN DATE_SUB(NOW(), INTERVAL 3 MONTH) AND NOW()
) AS ranger
ON ranger.ranger_date = counter.counter_date
ORDER BY ranger.ranger_date

我已经尝试过 createQuery 方法,但是没有用...

如果您的复杂本机 sql 查询成功返回了您想要的结果集:

你可以简单地 prepare and execute the query as documented by Symfony.
如果你需要水化实体,那么你可以使用 the NativeQuery class.