From 2a98f9b0d7b60ac3dd6377dfd9bbd6b36a32e930 Mon Sep 17 00:00:00 2001 From: Alexander Demidov Date: Mon, 28 Jul 2014 11:50:27 +0400 Subject: [PATCH] Correct detect count records in SQlCriteria with use group by --- Model/SqlCriteria.php | 9 +-------- Model/SqlModel.php | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Model/SqlCriteria.php b/Model/SqlCriteria.php index 42f78b1..841c68e 100644 --- a/Model/SqlCriteria.php +++ b/Model/SqlCriteria.php @@ -82,14 +82,7 @@ class SqlCriteria public function count() { $this->defineJoinExpressions(); - $sql_expression_backup = $this->sql_expression; - if ($this->sql_expression && !strstr('COUNT(*)', $this->sql_expression)) { - $this->sql_expression = preg_replace('#^SELECT .+ FROM#', 'SELECT COUNT(*) as count FROM', $this->sql_expression); - } else { - $this->sql_expression = 'SELECT COUNT(*) as count FROM :table'; - } - $count = $this->model->find(array(), '', $this->where, null, null, null, null, $this->sql_expression, $this->sql_expression_params)->fetchField('count'); - $this->sql_expression = $sql_expression_backup; + $count = $this->model->count(array(), '', $this->where, null, $this->group_by, $this->sql_expression, $this->sql_expression_params)->fetchField('count'); return $count; } diff --git a/Model/SqlModel.php b/Model/SqlModel.php index 3e9c919..8c797f5 100644 --- a/Model/SqlModel.php +++ b/Model/SqlModel.php @@ -226,6 +226,22 @@ abstract class SqlModel extends Model return new SqlResultProvider($result); } + public function count($select, $distinct, $where,$heaving = null, $group_by = null, $sql_expression = null, $sql_expression_params = array(), $cache_key = null) + { + $select = $this->db->selectExpr($select, $distinct); + $where = $this->db->whereExpr($where); + $group_by = $this->db->groupByExpr($group_by); + $result = $this->query( + 'SELECT COUNT(*) as count FROM (' . + (($sql_expression) ? $sql_expression : ('SELECT ' . $select . ' FROM ' . $this->identify($this->table()))) + . (($where) ? (' WHERE ' . $where) : '') + . (($group_by) ? (' GROUP BY ' . $group_by) : '') . ') AS x', + $sql_expression_params, + $cache_key + ); + return new SqlResultProvider($result); + } + /** * @param $sql_expression null * @param $sql_expression_params array