diff --git a/src/Mapping.php b/src/Mapping.php index 9227b8e..ba39c8c 100644 --- a/src/Mapping.php +++ b/src/Mapping.php @@ -82,6 +82,20 @@ public function findAll() return $this->map(parent::findAll()); } + /** + * Checks if any records exist matching the current conditions. + * + * @return bool + */ + public function exists() + { + if ($this->definition->getDeletionTimestamp()) { + $this->isNull($this->prefixTableNameTo($this->definition->getDeletionTimestamp())); + } + + return parent::exists(); + } + /** * Counts all records. * @@ -249,8 +263,7 @@ public function save(array $data) } } - $original = $this->findOne(); - return $original ? $this->update($data) : $this->insert($data); + return $this->exists() ? $this->update($data) : $this->insert($data); } /** diff --git a/tests/MappingTest.php b/tests/MappingTest.php index b7d31dc..56e3018 100644 --- a/tests/MappingTest.php +++ b/tests/MappingTest.php @@ -192,6 +192,19 @@ public function testRemove() ); } + public function testExists() + { + $this->assertTrue($this->getMapping()->eq('id', 1)->exists()); + $this->assertFalse($this->getMapping()->eq('id', 999)->exists()); + } + + public function testExistsReturnsFalseForSoftDeletedRecord() + { + $this->getMapping()->eq('id', 1)->remove(); + + $this->assertFalse($this->getMapping()->eq('id', 1)->exists()); + } + public function testReadOnlyInsert() { $customer = [