calculate() public method

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)
return string An SQL calculation function
 /**
  * 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);
 }
Example #2
0
 /**
  * test calculate to generate claculate statements on virtual fields
  *
  * @return void
  */
 public function testVirtualFieldsInCalculate()
 {
     $Boat = ClassRegistry::init('Boat');
     $commentsTable = $this->Dbo->fullTableName('comments', false, false);
     $Boat->virtualFields = array('this_moment' => 'NOW()', 'two' => '1 + 1', 'comment_count' => 'SELECT COUNT(*) FROM ' . $commentsTable . ' WHERE Boat.id = ' . $commentsTable . '.article_id');
     $result = $this->Dbo->calculate($Boat, 'count', array('this_moment'));
     $expected = 'COUNT(NOW()) AS `count`';
     $this->assertEquals($expected, $result);
     $result = $this->Dbo->calculate($Boat, 'max', array('comment_count'));
     $expected = "MAX(SELECT COUNT(*) FROM {$commentsTable} WHERE `Boat`.`id` = `{$commentsTable}`.`article_id`) AS `comment_count`";
     $this->assertEquals($expected, $result);
 }