Skip to content

Commit

Permalink
Added last() to Query
Browse files Browse the repository at this point in the history
  • Loading branch information
milesj committed Jun 18, 2014
1 parent b482808 commit a294b19
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Titon/Db/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,37 @@ public function intersect(Query $query, $flag = null) {
return $this->_addCompound(Dialect::INTERSECT, $query);
}

/**
* Return the last record from the results.
* Reverse the direction of any order by declarations.
*
* @param array $options
* @return \Titon\Db\Entity
*/
public function last(array $options = []) {
if ($order = $this->getOrderBy()) {
$this->_orderBy = [];

foreach ($order as $field => $dir) {
if ($dir === 'asc') {
$dir = 'desc';
} else if ($dir === 'desc') {
$dir = 'asc';
}

if (is_numeric($field)) {
$this->orderBy($dir);
} else {
$this->orderBy($field, $dir);
}
}
} else {
$this->orderBy($this->getRepository()->getPrimaryKey(), 'desc');
}

return $this->limit(1)->find('first', $options);
}

/**
* Add a new LEFT join.
*
Expand Down
34 changes: 34 additions & 0 deletions tests/Titon/Db/RepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,40 @@ public function testFindAllNoRecords() {
$this->assertEquals(new EntityCollection(), $this->object->select()->where('country_id', 15)->all());
}

public function testFindLast() {
$this->loadFixtures('Users');

$this->assertEquals(new Entity([
'id' => 5,
'country_id' => 4,
'username' => 'wolverine',
'firstName' => 'Logan',
'lastName' => '',
'password' => '1Z5895jf72yL77h',
'email' => 'wolverine@email.com',
'age' => 355,
'created' => '2000-11-30 21:22:34',
'modified' => null
]), $this->object->select()->last());
}

public function testFindLastReversedOrder() {
$this->loadFixtures('Users');

$this->assertEquals(new Entity([
'id' => 2,
'country_id' => 3,
'username' => 'batman',
'firstName' => 'Bruce',
'lastName' => 'Wayne',
'password' => '1Z5895jf72yL77h',
'email' => 'batman@email.com',
'age' => 35,
'created' => '1960-05-11 21:22:34',
'modified' => null
]), $this->object->select()->orderBy('lastName', 'asc')->last());
}

public function testFindList() {
$this->loadFixtures('Users');

Expand Down

0 comments on commit a294b19

Please sign in to comment.