【问题标题】:Sql to query builder - SymfonySql 查询生成器 - Symfony
【发布时间】:2018-11-20 14:00:03
【问题描述】:

我写了一个查询,需要过去 7 天并计算每天的支出金额。

 SELECT
 DATE(transaction_date) AS TransactionDate, 
 SUM(amount) AS Amount
 FROM transaction
 WHERE type = 'spend'
 AND transaction_date>=  DATE_ADD(NOW(), INTERVAL -7 DAY)
 GROUP BY TransactionDate

当我运行我的 sql 查询时,它工作正常,但我可能在我用 Symfony 编写的函数中弄错了。它返回 null,而上面的查询不是这样。

 public function getWeeklyTrans()
{
    $date = date('Y-m-d h:i:s', strtotime("-7 days"));

    $result = $this->getAmountRepository()
        ->createQueryBuilder('p')
        ->select('sum(abs(p.amount))')
        ->where('p.transactionDate BETWEEN :today AND :n7days')
        ->setParameter('today', date('Y-m-d h:i:s'))
        ->setParameter('n7days', $date)
        ->getQuery()
        ->getArrayResult();

    return $result;

}

【问题讨论】:

  • 查询并不完全相同——一个有一个额外的列和一个分组依据,并使用 >-= 而不是 BETWEEN。所以似乎更少关于 Symfony 语法,更多关于查询本身的组成......
  • 我对查询构建器不是 100% 熟悉,但你不应该在末尾使用 ->execute() 而不是 ->getArrayResult()
  • 可以,但这里不合逻辑。 @Dirk
  • 我在转换它时遇到了问题。我可以看出区别。 :(@ADyson
  • 还是一样的结果。 @Matteo

标签: php mysql sql symfony


【解决方案1】:

您不能从 Query Builder 获取 SQL 并将其与您的工作 Query 进行比较吗? $qb->getQuery()->getSQL() 之类的东西?

似乎错过了一些条件

  • type = 'spend'

  • transaction_date>= DATE_ADD(NOW(), INTERVAL -7 DAY) 不是完全相同的条件

  • GROUP BY TransactionDate 也不见了。

【讨论】:

    【解决方案2】:

    非常感谢。我找到了解决办法。

     public function getTrans()
    {
        $type = Transaction::TYPE_SPEND;
    
        $result = $this->getAmountRepository()
            ->createQueryBuilder('p')
            ->select('sum(p.amount)')
            ->where('p.transactionDate >= :end')
            ->andWhere('p.type >= :type')
            ->setParameter('end', new \DateTime('-7 days'))
            ->setParameter('type', $type)
            ->groupBy('p.transactionDate')
            ->getQuery()
            ->getResult();
    
        return $result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      相关资源
      最近更新 更多