Skip to content
Permalink
Browse files

Add Table::findOrNew()

This method lets you easily find an existing entity or generate a new
entity with the chosen properties. In addition to finding entities, it
lets you patch/set additional attributes on the found/created entity.

Refs #4631
  • Loading branch information...
markstory committed Sep 20, 2014
1 parent c24f7ca commit 015abf7cabc364619d4b9c86b0fdf70616246195
Showing with 55 additions and 0 deletions.
  1. +22 −0 src/ORM/Table.php
  2. +33 −0 tests/TestCase/ORM/TableTest.php
@@ -934,6 +934,28 @@ public function get($primaryKey, $options = []) {
));
}
/**
* Finds an existing record or creates a new record.
*
* Using the attributes defined in $search a find() will be done to locate
* an existing record. If that record exists it will be returned. If it does
* not exist, a new entity will be created. In both cases, the $additional properties
* will be patched into the entity.
*
* @param array $search The criteria to find existing records by.
* @param array $additional The array of additional attributes to patch into
* the new or existing entity.
* @return Cake\Datasource\EntityInterface An entity.
*/
public function findOrNew($search, $additional = []) {
$query = $this->find()->where($search);
$row = $query->first();
if ($row) {
return $this->patchEntity($row, $additional);
}
return $this->newEntity($search + $additional);
}
/**
* {@inheritDoc}
*/
@@ -3530,4 +3530,37 @@ public function testDebugInfo() {
$this->assertEquals($expected, $result);
}
/**
* Test the findOrNew method.
*
* @return void
*/
public function testFindOrNew() {
$articles = TableRegistry::get('Articles');
$article = $articles->findOrNew(['title' => 'Not there'], ['body' => 'New body']);
$this->assertTrue($article->isNew());
$this->assertNull($article->id);
$this->assertEquals('Not there', $article->title);
$this->assertEquals('New body', $article->body);
$article = $articles->findOrNew(['title' => 'First Article'], ['body' => 'New body']);
$this->assertFalse($article->isNew());
$this->assertNotNull($article->id);
$this->assertEquals('First Article', $article->title);
$this->assertEquals('New body', $article->body);
$article = $articles->findOrNew(
['author_id' => 2, 'title' => 'First Article'],
['published' => 'N', 'body' => 'New body']
);
$this->assertTrue($article->isNew());
$this->assertNull($article->id);
$this->assertEquals('First Article', $article->title);
$this->assertEquals('New body', $article->body);
$this->assertEquals('N', $article->published);
$this->assertEquals(2, $article->author_id);
}
}

0 comments on commit 015abf7

Please sign in to comment.
You can’t perform that action at this time.