Skip to content

Commit fa4a535

Browse files
wppdjenssegers
authored andcommitted
Fix query builder delete (#1130)
* fix query builder delete * tweak a bit * tweak the test
1 parent 163f726 commit fa4a535

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/Jenssegers/Mongodb/Query/Builder.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,13 @@ public function pluck($column, $key = null)
611611
*/
612612
public function delete($id = null)
613613
{
614+
// If an ID is passed to the method, we will set the where clause to check
615+
// the ID to allow developers to simply and quickly remove a single row
616+
// from their database without manually specifying the where clauses.
617+
if (! is_null($id)) {
618+
$this->where('_id', '=', $id);
619+
}
620+
614621
$wheres = $this->compileWheres();
615622
$result = $this->collection->DeleteMany($wheres);
616623
if (1 == (int) $result->isAcknowledged()) {

tests/QueryBuilderTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,40 @@ public function tearDown()
1111
DB::collection('items')->truncate();
1212
}
1313

14+
public function testDeleteWithId()
15+
{
16+
$user = DB::collection('users')->insertGetId([
17+
['name' => 'Jane Doe', 'age' => 20],
18+
]);
19+
20+
$user_id = (string) $user;
21+
22+
DB::collection('items')->insert([
23+
['name' => 'one thing', 'user_id' => $user_id],
24+
['name' => 'last thing', 'user_id' => $user_id],
25+
['name' => 'another thing', 'user_id' => $user_id],
26+
['name' => 'one more thing', 'user_id' => $user_id],
27+
]);
28+
29+
$product = DB::collection('items')->first();
30+
31+
$pid = (string) ($product['_id']);
32+
33+
DB::collection('items')->where('user_id', $user_id)->delete($pid);
34+
35+
$this->assertEquals(3, DB::collection('items')->count());
36+
37+
$product = DB::collection('items')->first();
38+
39+
$pid = $product['_id'];
40+
41+
DB::collection('items')->where('user_id', $user_id)->delete($pid);
42+
43+
DB::collection('items')->where('user_id', $user_id)->delete(str_random(32));
44+
45+
$this->assertEquals(2, DB::collection('items')->count());
46+
}
47+
1448
public function testCollection()
1549
{
1650
$this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', DB::collection('users'));

0 commit comments

Comments
 (0)