如何在cakephp 3获得上个月的总和

时间:2018-01-24 10:34:08

标签: cakephp cakephp-3.x

我需要获得上个月交易金额总和,我写了查询但收到错误Error: Call to undefined function App\Controller\YEAR()

// sum of total received amount 
  $conditions['transaction_type']=1;
  $conditions['AND']['YEAR(Transactions.created) >='] = YEAR('CURRENT_DATE - INTERVAL 1 MONTH');
  $conditions['AND']['MONTH(Transactions.created) <='] = MONTH('CURRENT_DATE - INTERVAL 1 MONTH');
  $query = $this->Transactions->find('all',['conditions'=>$conditions]); 
  $collection = new Collection($query);
  $sumOfReceivedAmount =  $collection->sumOf('amount');
  $this->set('sumOfReceivedAmount',$sumOfReceivedAmount);

我也尝试过使用查询构建器

$query = $this->Transactions->find()
               ->where(function ($exp, $q) {
                     $year = $q->func()->year([
                          'created' => 'identifier'
                     ]);
                     $month = $q->func()->month([
                          'created' => 'identifier'
                     ]);
                     return $exp
                     ->eq($year, $q->func()->year(['CURRENT_DATE - INTERVAL 1 MONTH']))
                     ->eq($month, $q->func()->month(['CURRENT_DATE - INTERVAL 1 MONTH']));
 });

对于这段代码,我得到了像

这样的查询
SELECT 
  *
FROM 
  transactions Transactions 
WHERE 
  (
    year(created) = (
      year(
        'CURRENT_DATE - INTERVAL 1 MONTH'
      )
    ) 
    AND month(created) = (
      month(
        'CURRENT_DATE - INTERVAL 1 MONTH'
      )
    )
  )

问题是这个单引号'CURRENT_DATE - INTERVAL 1 MONTH'

如何删除此单引号?

1 个答案:

答案 0 :(得分:2)

与您将其传递的值转换为year()的其他identifier用法类似,您必须将其他值声明为literal值(或传递表达式对象)这样它们就会按原样插入到查询中,而不是被绑定。

['CURRENT_DATE - INTERVAL 1 MONTH' => 'literal']

CakePHP还附带了表达类似功能的方法,特别是FunctionsBuilder::dateAdd()方法。此外,当将CURRENT_DATE表示为函数时,查询构建器将能够将SQL转换为其他DBMS,如SqlServer,它没有CURRENT_DATE

$q->func()->year(
    [$q->func()->dateAdd($q->func()->CURRENT_DATE(), -1, 'MONTH')]
)

NOW()也应该有效:

$q->func()->dateAdd($q->func()->now(), -1, 'MONTH')

另见