diff --git a/lib/Cake/Model/Model.php b/lib/Cake/Model/Model.php index 11011c877..b68ac9f3e 100644 --- a/lib/Cake/Model/Model.php +++ b/lib/Cake/Model/Model.php @@ -2537,19 +2537,23 @@ class Model extends Object implements CakeEventListener { } /** - * Returns true if a record with the currently set ID exists. + * Returns true if a record with particular ID exists. * - * Internally calls Model::getID() to obtain the current record ID to verify, + * If $id is not passed it calls Model::getID() to obtain the current record ID, * and then performs a Model::find('count') on the currently configured datasource * to ascertain the existence of the record in persistent storage. * + * @param mixed $id ID of record to check for existence * @return boolean True if such a record exists */ - public function exists() { - if ($this->getID() === false) { + public function exists($id = null) { + if ($id === null) { + $id = $this->getID(); + } + if ($id === false) { return false; } - $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID()); + $conditions = array($this->alias . '.' . $this->primaryKey => $id); $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false); return ($this->find('count', $query) > 0); } diff --git a/lib/Cake/Test/Case/Model/ModelReadTest.php b/lib/Cake/Test/Case/Model/ModelReadTest.php index f4d1ceb33..5292670dc 100644 --- a/lib/Cake/Test/Case/Model/ModelReadTest.php +++ b/lib/Cake/Test/Case/Model/ModelReadTest.php @@ -24,6 +24,25 @@ require_once dirname(__FILE__) . DS . 'ModelTestBase.php'; */ class ModelReadTest extends BaseModelTest { +/** + * testExists function + * @retun void + */ + public function testExists() { + $this->loadFixtures('User'); + $TestModel = new User(); + + $this->assertTrue($TestModel->exists(1)); + + $TestModel->id = 2; + $this->assertTrue($TestModel->exists()); + + $TestModel->delete(); + $this->assertFalse($TestModel->exists()); + + $this->assertFalse($TestModel->exists(2)); + } + /** * testFetchingNonUniqueFKJoinTableRecords() * @@ -7784,18 +7803,18 @@ class ModelReadTest extends BaseModelTest { $this->assertEquals($Post->getVirtualField('other_field'), $Post->virtualFields['other_field']); $this->assertEquals($Post->getVirtualField('Post.other_field'), $Post->virtualFields['other_field']); } - - + + /** * test that checks for error when NOT condition passed in key and a 1 element array value * * @return void - */ + */ public function testNotInArrayWithOneValue() { $this->loadFixtures('Article'); $Article = new Article(); $Article->recursive = -1; - + $result = $Article->find( 'all', array( @@ -7804,7 +7823,7 @@ class ModelReadTest extends BaseModelTest { ) ) ); - + $this->assertTrue(is_array($result) && !empty($result)); } }