From 3e2024e2058cc5e92b14aba2a2821fe66e93cb62 Mon Sep 17 00:00:00 2001 From: Ryan Rigby <16025441+rrigby@users.noreply.github.com> Date: Sat, 7 Mar 2026 11:03:23 +1000 Subject: [PATCH] Override exists and use it when saving to prevent mapping the entire object twice. --- src/Mapping.php | 17 +++++++++++++++-- tests/MappingTest.php | 13 +++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) 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 = [