Browse Source

Merge pull request #8707 from burzum/feature/find-or-create

Feature/find or create
José Lorenzo Rodríguez 10 years ago
parent
commit
2c074445ae
2 changed files with 24 additions and 2 deletions
  1. 18 2
      src/ORM/Table.php
  2. 6 0
      tests/TestCase/ORM/TableTest.php

+ 18 - 2
src/ORM/Table.php

@@ -1213,7 +1213,9 @@ class Table implements RepositoryInterface, EventListenerInterface, EventDispatc
      * called allowing you to define additional default values. The new
      * entity will be saved and returned.
      *
-     * @param array $search The criteria to find existing records by.
+     * @param array|\Cake\ORM\Query $search The criteria to find existing
+     *   records by. Note that when you pass a query object you'll have to use
+     *   the 2nd arg of the method to modify the entity data before saving.
      * @param callable|null $callback A callback that will be invoked for newly
      *   created entities. This callback will be called *before* the entity
      *   is persisted.
@@ -1221,7 +1223,7 @@ class Table implements RepositoryInterface, EventListenerInterface, EventDispatc
      */
     public function findOrCreate($search, callable $callback = null)
     {
-        $query = $this->find()->where($search);
+        $query = $this->_getFindOrCreateQuery($search);
         $row = $query->first();
         if ($row) {
             return $row;
@@ -1235,6 +1237,20 @@ class Table implements RepositoryInterface, EventListenerInterface, EventDispatc
     }
 
     /**
+     * Gets the query object for findOrCreate().
+     *
+     * @param array|\Cake\ORM\Query|string $search The criteria to find existing records by.
+     * @return \Cake\ORM\Query
+     */
+    protected function _getFindOrCreateQuery($search)
+    {
+        if ($search instanceof Query) {
+            return $search;
+        }
+        return $this->find()->where($search);
+    }
+
+    /**
      * {@inheritDoc}
      */
     public function query()

+ 6 - 0
tests/TestCase/ORM/TableTest.php

@@ -5383,6 +5383,12 @@ class TableTest extends TestCase
         $this->assertEquals('New body', $article->body);
         $this->assertEquals('N', $article->published);
         $this->assertEquals(2, $article->author_id);
+
+        $query = $articles->find()->where(['author_id' => 2, 'title' => 'First Article']);
+        $article = $articles->findOrCreate($query);
+        $this->assertEquals('First Article', $article->title);
+        $this->assertEquals(2, $article->author_id);
+        $this->assertFalse($article->isNew());
     }
 
     /**