From a8a2ae74151b5a77b5f47204f946512616b264d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 31 Aug 2023 18:16:48 +0200 Subject: [PATCH] Support delete one document --- src/Query/Builder.php | 9 ++++++++- tests/QueryTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 50b3ba34f..85efd14f3 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -703,7 +703,14 @@ public function delete($id = null) $wheres = $this->compileWheres(); $options = $this->inheritConnectionOptions(); - $result = $this->collection->deleteMany($wheres, $options); + if ($this->limit) { + if ($this->limit !== 1) { + throw new \InvalidArgumentException('Cannot delete more than 1 document when using limit'); + } + $result = $this->collection->deleteOne($wheres, $options); + } else { + $result = $this->collection->deleteMany($wheres, $options); + } if (1 == (int) $result->isAcknowledged()) { return $result->getDeletedCount(); diff --git a/tests/QueryTest.php b/tests/QueryTest.php index 03713ffae..d982f45b5 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -548,4 +548,28 @@ public function testMultipleSortOrder(): void $this->assertEquals('John Doe', $subset[1]->name); $this->assertEquals('Brett Boe', $subset[2]->name); } + + public function testDelete(): void + { + $this->assertEquals(3, User::where('title', 'admin')->count()); + + // Delete a single document with filter + User::where('title', 'admin')->limit(1)->delete(); + $this->assertEquals(2, User::where('title', 'admin')->count()); + + // Delete all with filter + User::where('title', 'admin')->delete(); + $this->assertEquals(0, User::where('title', 'admin')->count()); + + // Check remaining fixtures + $this->assertEquals(6, User::count()); + + // Delete a single document + User::limit(1)->delete(); + $this->assertEquals(5, User::count()); + + // Delete all + User::limit(null)->delete(); + $this->assertEquals(0, User::count()); + } }