Skip to content

Commit

Permalink
Issue #24 Add group_by_expr function
Browse files Browse the repository at this point in the history
  • Loading branch information
treffynnon committed Nov 12, 2012
1 parent 22e24b1 commit b879551
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
7 changes: 6 additions & 1 deletion README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Changelog
* Patch to allow empty Paris models to be saved ([[j4mie/paris](http://github.com/j4mie/paris)]) issue #58
* Add `select_many` and `select_many_expr` - closing issues #49 and #69
* Add support for `MIN`, `AVG`, `MAX` and `SUM` - closes issue #16
* Add `group_by_expr` - closes issue #24

#### 1.1.1 - release 2011-01-30

Expand Down Expand Up @@ -230,7 +231,11 @@ If you want to order by something other than a column name, then use the `order_

To add a `GROUP BY` clause to your query, call the `group_by` method, passing in the column name. You can call this method multiple times to add further columns.

$poeple = ORM::for_table('person')->where('gender', 'female')->group_by('name')->find_many();
$people = ORM::for_table('person')->where('gender', 'female')->group_by('name')->find_many();

It is also possible to `GROUP BY` a database expression:

$people = ORM::for_table('person')->where('gender', 'female')->group_by_expr("FROM_UNIXTIME(`time`, '%Y-%m')")->find_many();

#### Result columns ####

Expand Down
8 changes: 8 additions & 0 deletions idiorm.php
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,14 @@ public function group_by($column_name) {
return $this;
}

/**
* Add an unquoted expression to the list of columns to GROUP BY
*/
public function group_by_expr($expr) {
$this->_group_by[] = $expr;
return $this;
}

/**
* Build a SELECT statement based on the clauses that have
* been passed to this instance by chaining method calls.
Expand Down
4 changes: 4 additions & 0 deletions test/test_queries.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@
$expected = "SELECT * FROM `widget` GROUP BY `name`, `age`";
Tester::check_equal("Multiple GROUP BY", $expected);

ORM::for_table('widget')->group_by_expr("FROM_UNIXTIME(`time`, '%Y-%m')")->find_many();
$expected = "SELECT * FROM `widget` GROUP BY FROM_UNIXTIME(`time`, '%Y-%m')";
Tester::check_equal("GROUP BY expression", $expected);

ORM::for_table('widget')->where('name', 'Fred')->limit(5)->offset(5)->order_by_asc('name')->find_many();
$expected = "SELECT * FROM `widget` WHERE `name` = 'Fred' ORDER BY `name` ASC LIMIT 5 OFFSET 5";
Tester::check_equal("Complex query", $expected);
Expand Down

0 comments on commit b879551

Please sign in to comment.