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()); + } }