Symofny-查询总金额

时间:2018-11-20 09:56:06

标签: php mysql sum

我正在编写一个查询,该查询将返回该用户的总花费金额。总支出=所有交易金额的总和,其中类型=支出。我已将基本类型字段设置为“花费”。

返回

  

参数无效:查询中未定义令牌类型。

我的代码。

public function getTotal(User $user, $type)
{
    $query = $this->getSpendingRepository()
        ->createQueryBuilder('p')
        ->select("sum(p.amount) as total_amount")
        ->where('p.type = :spend')
        ->andWhere('p.user = :user')
        ->setParameters(['user' => $user,
                         'type' => $type])
        ->getQuery()
        ->getOneOrNullResult();

    return $query;
}

这是正在运行的sql,所以我不知道我在做什么错。.

select user_id, sum(amount) as amount
from transaction
where type = 'spend'
group by user_id

2 个答案:

答案 0 :(得分:0)

替换

->where('p.type = :spend')

使用

->where('p.type = :type')

答案 1 :(得分:0)

我修复了。

 public function getTotalSpent(User $user, $type = 'spend')
{
    $query = $this->getTransactionRepository()
        ->createQueryBuilder('p')
        ->select("sum(p.amount) as total_amount")
        ->where('p.type = :type')
        ->andWhere('p.user = :user')
        ->setParameters(['user' => $user,
                         'type' => $type])
        ->getQuery()
        ->getOneOrNullResult();

    return $query;
}