Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should limit === 0 be supported? Or would Eloquent expect that to be a NOP?

I suppose the notion of limit: 0 meaning "delete all" is an implementation detail of MongoDB's delete command and not a general concept, so I'm fine with not supporting that.

I do wonder if we should have a separate exception message if 0 is specified that advises users to specify null instead (or not call limit() at all), as this message might confuse a user with more experience with MongoDB than Eloquent.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're absolutely right. I've also banned 0.

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