Skip to content

Commit

Permalink
Support delete one document
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN committed Aug 31, 2023
1 parent ab02a25 commit a8a2ae7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
24 changes: 24 additions & 0 deletions tests/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}

0 comments on commit a8a2ae7

Please sign in to comment.