Skip to content

Commit bf195f0

Browse files
committed
Support delete one document
1 parent 9d36d17 commit bf195f0

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/Query/Builder.php

+8-1
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 (is_int($this->limit)) {
707+
if ($this->limit !== 1) {
708+
throw new \LogicException(sprintf('Delete limit can be 1 or null (unlimited). Got %d', $this->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

+36
Original file line numberDiff line numberDiff line change
@@ -548,4 +548,40 @@ 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+
// Check fixtures
555+
$this->assertEquals(3, User::where('title', 'admin')->count());
556+
557+
// Delete a single document with filter
558+
User::where('title', 'admin')->limit(1)->delete();
559+
$this->assertEquals(2, User::where('title', 'admin')->count());
560+
561+
// Delete all with filter
562+
User::where('title', 'admin')->delete();
563+
$this->assertEquals(0, User::where('title', 'admin')->count());
564+
565+
// Check remaining fixtures
566+
$this->assertEquals(6, User::count());
567+
568+
// Delete a single document
569+
User::limit(1)->delete();
570+
$this->assertEquals(5, User::count());
571+
572+
// Delete all
573+
User::limit(null)->delete();
574+
$this->assertEquals(0, User::count());
575+
}
576+
577+
/**
578+
* @testWith [0]
579+
* [2]
580+
*/
581+
public function testDeleteException(int $limit): void
582+
{
583+
$this->expectException(\LogicException::class);
584+
$this->expectExceptionMessage('Delete limit can be 1 or null (unlimited).');
585+
User::limit($limit)->delete();
586+
}
551587
}

0 commit comments

Comments
 (0)