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 5c0dd54
Show file tree
Hide file tree
Showing 2 changed files with 44 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 (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();
Expand Down
36 changes: 36 additions & 0 deletions tests/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

0 comments on commit 5c0dd54

Please sign in to comment.