diff --git a/model/SqlCriteria.php b/model/SqlCriteria.php index 3da0777..d0f1041 100644 --- a/model/SqlCriteria.php +++ b/model/SqlCriteria.php @@ -8,6 +8,8 @@ class SqlCriteria private $where = array(); + private $group_by = array(); + private $order = array('sort' => array(), 'order' => array()); private $limit = ''; @@ -38,7 +40,7 @@ class SqlCriteria */ public function find() { - return $this->model->find($this->select, $this->distinct, $this->where, $this->order, $this->limit, null, null, $this->sql_expression, $this->sql_expression_params); + return $this->model->find($this->select, $this->distinct, $this->where, $this->order, $this->limit, null, $this->group_by, $this->sql_expression, $this->sql_expression_params); } public function count() @@ -96,6 +98,16 @@ class SqlCriteria return $this->whereNotIn($field, $value); } + public function groupBy($fields) + { + if (is_array($fields)) { + $this->group_by = $this->group_by + $fields; + } else { + $this->group_by[] = $fields; + } + return $this; + } + /** * @param $field string Field @ex 'field' * @param $order_desc bool Descendant sort direction diff --git a/model/SqlDbDriver.php b/model/SqlDbDriver.php index 83014c6..5e13557 100644 --- a/model/SqlDbDriver.php +++ b/model/SqlDbDriver.php @@ -159,6 +159,30 @@ abstract class SqlDbDriver extends DbDriver } /** + * @param mixed $group_by + * @return string + * @throws ErrorException + */ + public function groupByExpr($group_by) + { + if (empty($group_by)) { + return $group_by; + } + + if (!is_array($group_by)) { + $group_by = array($group_by); + } + foreach ($group_by as &$term) { + if ($term instanceof DbExpr) { + $term = (string) $term; + } else { + $term = $this->quoteIdentifier($term); + } + } + return implode(',', $group_by); + } + + /** * @param $select array * @param $distinct string|bool * @return string diff --git a/model/SqlModel.php b/model/SqlModel.php index f99c414..7b5154a 100644 --- a/model/SqlModel.php +++ b/model/SqlModel.php @@ -206,11 +206,13 @@ abstract class SqlModel extends Model { $select = $this->db->selectExpr($select, $distinct); $where = $this->db->whereExpr($where); + $group_by = $this->db->groupByExpr($group_by); $order = isset($order['sort']) ? $this->order($order, $order['sort']) : false; $limit = $this->db->limitExpr($limit); $result_items = $this->fetchAll( (($sql_expression) ? $sql_expression : ('SELECT ' . $select . ' FROM ' . $this->table())) . (($where) ? (' WHERE ' . $where) : '') + . (($group_by) ? (' GROUP BY ' . $group_by) : '') . (($order) ? ($order) : '') . (($limit) ? (' LIMIT ' . $limit) : ''), $sql_expression_params,