Skip to content

[9.x] Fix clone issue on updateOrCreate and firstOrCreate#42434

Merged
taylorotwell merged 1 commit into
laravel:9.xfrom
deefour:bugfix/belongs-to-many-query-clone
May 19, 2022
Merged

[9.x] Fix clone issue on updateOrCreate and firstOrCreate#42434
taylorotwell merged 1 commit into
laravel:9.xfrom
deefour:bugfix/belongs-to-many-query-clone

Conversation

@deefour

@deefour deefour commented May 19, 2022

Copy link
Copy Markdown
Contributor

#42087 breaks functionality on BelongsToMany with a custom pivot table/model for updateOrCreate() and firstOrCreate().

The current behavior,

$instance = $this->clone()->where($attributes)->first()

is creating an issue in which all columns from the pivot table are applied to $instance. This isn't expected behavior in general, but is a breaking change introduced in #42087 when the pivot table has a primary key matching the source model - $instance->id will end up being the id from the pivot table, not the target table the firstOrCreate() or updateOrCreate() is pointing to.

The chain of magic __call and __clone methods between Relation, Eloquent\Builder and Query\Builder is a bit hard to follow. This is compounded by the fact that $this->clone() uses the ForwardsCalls trait to delegate the call into Eloquent\Builder, returning an instance of that builder instead of a copy of `Relation.

(clone $this) - directly cloning the Relation to do the $instance query keeps the pivot table data out of $instance.

/cc @trideout

@taylorotwell
taylorotwell merged commit bea761c into laravel:9.x May 19, 2022
@GrahamCampbell GrahamCampbell changed the title Fix clone issue on updateOrCreate and firstOrCreate [9.x] Fix clone issue on updateOrCreate and firstOrCreate Jun 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants