Skip to content

Fix query builder delete #1130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from Feb 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 7 additions & 0 deletions src/Jenssegers/Mongodb/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,13 @@ public function pluck($column, $key = null)
*/
public function delete($id = null)
{
// If an ID is passed to the method, we will set the where clause to check
// the ID to allow developers to simply and quickly remove a single row
// from their database without manually specifying the where clauses.
if (! is_null($id)) {
$this->where('_id', '=', $id);
}

$wheres = $this->compileWheres();
$result = $this->collection->DeleteMany($wheres);
if (1 == (int) $result->isAcknowledged()) {
Expand Down
34 changes: 34 additions & 0 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,40 @@ public function tearDown()
DB::collection('items')->truncate();
}

public function testDeleteWithId()
{
$user = DB::collection('users')->insertGetId([
['name' => 'Jane Doe', 'age' => 20],
]);

$user_id = (string) $user;

DB::collection('items')->insert([
['name' => 'one thing', 'user_id' => $user_id],
['name' => 'last thing', 'user_id' => $user_id],
['name' => 'another thing', 'user_id' => $user_id],
['name' => 'one more thing', 'user_id' => $user_id],
]);

$product = DB::collection('items')->first();

$pid = (string) ($product['_id']);

DB::collection('items')->where('user_id', $user_id)->delete($pid);

$this->assertEquals(3, DB::collection('items')->count());

$product = DB::collection('items')->first();

$pid = $product['_id'];

DB::collection('items')->where('user_id', $user_id)->delete($pid);

DB::collection('items')->where('user_id', $user_id)->delete(str_random(32));

$this->assertEquals(2, DB::collection('items')->count());
}

public function testCollection()
{
$this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', DB::collection('users'));
Expand Down