我真正需要的是:用Symfony2中的QueryBuilder返回上个月的记录
或者换句话说:将下面的MySQL查询转换为Doctrine QueryBuilder

created_at >= DATE_FORMAT(NOW(), '%Y-%m-%d') - INTERVAL 1 MONTH

我所做的:
$clicks = $clickRepo->createQueryBuilder('c')
        ->select('c.product, c.createdAt, c.title')
        ->addSelect('COUNT(c.product)')
        ->where('c.type = :pro')
            ->setParameter('pro', 'product')
        ->andWhere('c.createdAt >= DATE_DIFF(CURRENT_DATE(), :end)')
            ->setParameter('end', new \DateTime('-30 days'), \Doctrine\DBAL\Types\Type::DATETIME)
        ->andWhere('c.shop != :null')
            ->setParameter('null', '0')
        ->andWhere('c.visible = :one')
            ->setParameter('one', '1')
        ->groupBy('c.product')
        ->setMaxResults(2)
        ->getQuery()->getResult();

结果:
array(1) {
  [0]=>
  array(4) {
    ["product"]=>
    int(3)
    ["createdAt"]=>
    object(DateTime)#3211 (3) {
      ["date"]=>
      string(26) "2016-02-19 13:27:45.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(13) "Europe/Berlin"
    }
    ["title"]=>
    string(23) "Title BlaBla"
    ["clicks"]=>
    string(1) "2"
  }
}

它只返回表开头的记录。

最佳答案

DATE_DIFF()返回两个日期之间的时间。我认为您必须使用DATE_SUB()函数。
->andWhere('c.createdAt>=DATE_SUB(CURRENT_DATE(),:end)')

关于php - 如何使用QueryBuilder计算CURRENT_DATE()和上个月的天数差异?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41508208/

10-11 05:40