DboSource::calculate PHP 메소드

calculate() 공개 메소드

Returns an SQL calculation, i.e. COUNT() or MAX()
public calculate ( Model $Model, string $func, array $params = [] ) : string
$Model Model The model to get a calculated field for.
$func string Lowercase name of SQL function, i.e. 'count' or 'max'
$params array Function parameters (any values must be quoted manually)
리턴 string An SQL calculation function
    public function calculate(Model $Model, $func, $params = array())
    {
        $params = (array) $params;
        switch (strtolower($func)) {
            case 'count':
                if (!isset($params[0])) {
                    $params[0] = '*';
                }
                if (!isset($params[1])) {
                    $params[1] = 'count';
                }
                if ($Model->isVirtualField($params[0])) {
                    $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
                } else {
                    $arg = $this->name($params[0]);
                }
                return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
            case 'max':
            case 'min':
                if (!isset($params[1])) {
                    $params[1] = $params[0];
                }
                if ($Model->isVirtualField($params[0])) {
                    $arg = $this->_quoteFields($Model->getVirtualField($params[0]));
                } else {
                    $arg = $this->name($params[0]);
                }
                return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
        }
    }

Usage Example

 /**
  * test calculate to generate claculate statements on virtual fields
  *
  * @return void
  */
 function testVirtualFieldsInCalculate()
 {
     $Article = ClassRegistry::init('Article');
     $Article->virtualFields = array('this_moment' => 'NOW()', 'two' => '1 + 1', 'comment_count' => 'SELECT COUNT(*) FROM ' . $this->Dbo->fullTableName('comments') . ' WHERE Article.id = ' . $this->Dbo->fullTableName('comments') . '.article_id');
     $result = $this->Dbo->calculate($Article, 'count', array('this_moment'));
     $expected = 'COUNT(NOW()) AS `count`';
     $this->assertEqual($expected, $result);
     $result = $this->Dbo->calculate($Article, 'max', array('comment_count'));
     $expected = 'MAX(SELECT COUNT(*) FROM comments WHERE `Article`.`id` = `comments`.`article_id`) AS `comment_count`';
     $this->assertEqual($expected, $result);
 }
All Usage Examples Of DboSource::calculate
DboSource