Php Sql查询生成器-Symfony
我写了一个查询,需要花费最后7天的时间来计算每天的支出金额Php Sql查询生成器-Symfony,php,mysql,sql,symfony,Php,Mysql,Sql,Symfony,我写了一个查询,需要花费最后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查询时,它工作正常
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;
}
难道您不能从查询生成器中获取SQL并将其保存到您的工作查询中吗? 类似于
$qb->getQuery()->getSQL()
似乎它错过了一些条件
type='spend'
的条件不完全相同transaction\u date>=date\u ADD(现在(),间隔-7天)
- 也缺少按交易日期分组的
- 非常感谢您。我找到了解决办法
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;
}
这些查询并不完全相同-一个查询有一个额外的列和一个GROUPBY,并使用>-=而不是BETWEEN。因此,似乎不太关注Symfony语法,而更关注查询本身的组成……我对querybuilder不是100%熟悉,但您不应该在末尾使用
->execute()
,而不是->getArrayResult()
?它可以,但这里不是逻辑@DirkI在转换它时遇到了问题。我看到了不同(@adysons)直到同样的结果。@Matteo