Skip to content

Commit cc66b3a

Browse files
goodevilgeniusjenssegers
authored andcommitted
Get base query before update so that scopes are applied (#1799)
Fixes #1798
1 parent b9cc872 commit cc66b3a

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

src/Jenssegers/Mongodb/Eloquent/Builder.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public function update(array $values, array $options = [])
4444
return 1;
4545
}
4646

47-
return $this->query->update($this->addUpdatedAtColumn($values), $options);
47+
return $this->toBase()->update($this->addUpdatedAtColumn($values), $options);
4848
}
4949

5050
/**

tests/QueryTest.php

+18
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ public function setUp(): void
2121
public function tearDown(): void
2222
{
2323
User::truncate();
24+
Scoped::truncate();
2425
parent::tearDown();
2526
}
2627

@@ -309,4 +310,21 @@ public function testPaginate()
309310
$this->assertEquals(9, $results->total());
310311
$this->assertEquals(1, $results->currentPage());
311312
}
313+
314+
public function testUpdate()
315+
{
316+
$this->assertEquals(1, User::where(['name' => 'John Doe'])->update(['name' => 'Jim Morrison']));
317+
$this->assertEquals(1, User::where(['name' => 'Jim Morrison'])->count());
318+
319+
Scoped::create(['favorite' => true]);
320+
Scoped::create(['favorite' => false]);
321+
322+
$this->assertCount(1, Scoped::get());
323+
$this->assertEquals(1, Scoped::query()->update(['name' => 'Johnny']));
324+
$this->assertCount(1, Scoped::withoutGlobalScopes()->where(['name' => 'Johnny'])->get());
325+
326+
$this->assertCount(2, Scoped::withoutGlobalScopes()->get());
327+
$this->assertEquals(2, Scoped::withoutGlobalScopes()->update(['name' => 'Jimmy']));
328+
$this->assertCount(2, Scoped::withoutGlobalScopes()->where(['name' => 'Jimmy'])->get());
329+
}
312330
}

tests/models/Scoped.php

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
4+
use Jenssegers\Mongodb\Eloquent\Builder;
5+
6+
class Scoped extends Eloquent
7+
{
8+
protected $connection = 'mongodb';
9+
protected $collection = 'scoped';
10+
protected $fillable = ['name', 'favorite'];
11+
12+
protected static function boot()
13+
{
14+
parent::boot();
15+
16+
static::addGlobalScope('favorite', function (Builder $builder) {
17+
$builder->where('favorite', true);
18+
});
19+
}
20+
}

0 commit comments

Comments
 (0)