Skip to content
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

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

Merged

Conversation

deefour
Copy link
Contributor

@deefour deefour commented May 19, 2022

#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