From 5c0dd54e44581e84505fe7242771f1468e11e2c7 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 | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 50b3ba34f..6a37e1608 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 (is_int($this->limit)) { + if ($this->limit !== 1) { + throw new \LogicException(sprintf('Delete limit can be 1 or null (unlimited). Got %d', $this->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..2a9bd4085 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -548,4 +548,40 @@ public function testMultipleSortOrder(): void $this->assertEquals('John Doe', $subset[1]->name); $this->assertEquals('Brett Boe', $subset[2]->name); } + + public function testDelete(): void + { + // Check fixtures + $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()); + } + + /** + * @testWith [0] + * [2] + */ + public function testDeleteException(int $limit): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('Delete limit can be 1 or null (unlimited).'); + User::limit($limit)->delete(); + } }