Skip to content

Commit a8a2ae7

Browse files
committed
Support delete one document
1 parent ab02a25 commit a8a2ae7

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Query/Builder.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -703,7 +703,14 @@ public function delete($id = null)
703703
$wheres = $this->compileWheres();
704704
$options = $this->inheritConnectionOptions();
705705

706-
$result = $this->collection->deleteMany($wheres, $options);
706+
if ($this->limit) {
707+
if ($this->limit !== 1) {
708+
throw new \InvalidArgumentException('Cannot delete more than 1 document when using limit');
709+
}
710+
$result = $this->collection->deleteOne($wheres, $options);
711+
} else {
712+
$result = $this->collection->deleteMany($wheres, $options);
713+
}
707714

708715
if (1 == (int) $result->isAcknowledged()) {
709716
return $result->getDeletedCount();

tests/QueryTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,4 +548,28 @@ public function testMultipleSortOrder(): void
548548
$this->assertEquals('John Doe', $subset[1]->name);
549549
$this->assertEquals('Brett Boe', $subset[2]->name);
550550
}
551+
552+
public function testDelete(): void
553+
{
554+
$this->assertEquals(3, User::where('title', 'admin')->count());
555+
556+
// Delete a single document with filter
557+
User::where('title', 'admin')->limit(1)->delete();
558+
$this->assertEquals(2, User::where('title', 'admin')->count());
559+
560+
// Delete all with filter
561+
User::where('title', 'admin')->delete();
562+
$this->assertEquals(0, User::where('title', 'admin')->count());
563+
564+
// Check remaining fixtures
565+
$this->assertEquals(6, User::count());
566+
567+
// Delete a single document
568+
User::limit(1)->delete();
569+
$this->assertEquals(5, User::count());
570+
571+
// Delete all
572+
User::limit(null)->delete();
573+
$this->assertEquals(0, User::count());
574+
}
551575
}

0 commit comments

Comments
 (0)