Browse Source

Add group by support in sql criteria.

namespace
Alexander Demidov 11 years ago
parent
commit
4878b32641
  1. 14
      model/SqlCriteria.php
  2. 24
      model/SqlDbDriver.php
  3. 2
      model/SqlModel.php

14
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

24
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

2
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,

Loading…
Cancel
Save