Skip to content

Commit

Permalink
fix clone issue on updateOrCreate and firstOrCreate (#42434)
Browse files Browse the repository at this point in the history
Co-authored-by: Jason Daly <[email protected]>
  • Loading branch information
deefour and Jason Daly authored May 19, 2022
1 parent 534188b commit bea761c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ public function firstOrNew(array $attributes = [], array $values = [])
*/
public function firstOrCreate(array $attributes = [], array $values = [], array $joining = [], $touch = true)
{
if (is_null($instance = $this->clone()->where($attributes)->first())) {
if (is_null($instance = (clone $this)->where($attributes)->first())) {
if (is_null($instance = $this->related->where($attributes)->first())) {
$instance = $this->create(array_merge($attributes, $values), $joining, $touch);
} else {
Expand All @@ -640,7 +640,7 @@ public function firstOrCreate(array $attributes = [], array $values = [], array
*/
public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true)
{
if (is_null($instance = $this->clone()->where($attributes)->first())) {
if (is_null($instance = (clone $this)->where($attributes)->first())) {
if (is_null($instance = $this->related->where($attributes)->first())) {
return $this->create(array_merge($attributes, $values), $joining, $touch);
} else {
Expand Down
36 changes: 36 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,42 @@ public function testFirstOrMethod()
})->id
);
}

public function testUpdateOrCreateQueryBuilderIsolation()
{
$user = User::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);

$user->postsWithCustomPivot()->attach($post);

$instance = $user->postsWithCustomPivot()->updateOrCreate(
['uuid' => $post->uuid],
['title' => Str::random()],
);

$this->assertArrayNotHasKey(
'user_uuid',
$instance->toArray(),
);
}

public function testFirstOrCreateQueryBuilderIsolation()
{
$user = User::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);

$user->postsWithCustomPivot()->attach($post);

$instance = $user->postsWithCustomPivot()->firstOrCreate(
['uuid' => $post->uuid],
['title' => Str::random()],
);

$this->assertArrayNotHasKey(
'user_uuid',
$instance->toArray(),
);
}
}

class User extends Model
Expand Down

0 comments on commit bea761c

Please sign in to comment.