Skip to content

Commit

Permalink
Implementing automatic updating for Table::save()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Oct 27, 2013
1 parent 9615798 commit 72e9eeb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Cake/ORM/Table.php
Expand Up @@ -775,7 +775,19 @@ protected function _insert($entity, $data) {
}

protected function _update($entity, $data) {
$query = $this->_buildQuery();
$primaryKey = $entity->extract((array)$this->primaryKey());
$statement = $query->update($this->table())
->set($data)
->where($primaryKey)
->executeStatement();

$success = false;
if ($statement->rowCount() > 0) {
$entity->clean();
$success = $entity;
}
return $success;
}

/**
Expand Down
22 changes: 22 additions & 0 deletions Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -1342,4 +1342,26 @@ public function testsASavedEntityIsNotNew() {
$this->assertFalse($entity->isNew());
}

/**
* Tests that save can detect automatically if it needs to insert
* or update a row
*
* @return void
*/
public function testSaveUpdateAuto() {
$entity = new \Cake\ORM\Entity([
'id' => 2,
'username' => 'baggins'
]);
$table = TableRegistry::get('users');
$original = $table->find('all')->where(['id' => 2])->first();
$this->assertSame($entity, $table->save($entity));
$row = $table->find('all')->where(['id' => 2])->first();
$this->assertEquals('baggins', $row->username);
$this->assertEquals($original->password, $row->password);
$this->assertEquals($original->created, $row->created);
$this->assertEquals($original->updated, $row->updated);
}


}

0 comments on commit 72e9eeb

Please sign in to comment.