diff --git a/src/ORM/Table.php b/src/ORM/Table.php index f42ed184e0f..8134fd99a6a 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -1677,10 +1677,19 @@ public function findOrCreate($search, callable $callback = null, $options = []) { $options += [ 'atomic' => true, - 'defaults' => true + 'defaults' => true, + '_primary' => true, ]; - return $this->_processFindOrCreate($search, $callback, $options); + $entity = $this->_executeTransaction(function () use ($search, $callback, $options) { + return $this->_processFindOrCreate($search, $callback, $options); + }, $options['atomic']); + + if ($entity && $this->_transactionCommitted($options['atomic'], $options['_primary'])) { + $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options')); + } + + return $entity; } /** diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index 3be3bd22aac..cb64a03de53 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -6157,9 +6157,11 @@ public function testFindOrCreateTransactions() $article = $articles->findOrCreate(function ($query) { $this->assertInstanceOf('Cake\ORM\Query', $query); $query->where(['title' => 'Find Something New']); + $this->assertTrue($this->connection->inTransaction()); }, function ($article) { $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article); $article->title = 'Success'; + $this->assertTrue($this->connection->inTransaction()); }); $this->assertFalse($article->isNew()); $this->assertNotNull($article->id);