8000 [9.x] Consistent BelongsToMany::firstOrCreate behaviour by tw99 · Pull Request #37337 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content

[9.x] Consistent BelongsToMany::firstOrCreate behaviour #37337

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

Merged
merged 1 commit into from
May 12, 2021

Conversation

tw99
Copy link
Contributor
@tw99 tw99 commented May 10, 2021

From Laravel documentation:

The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument

This is the current behaviour for other instances of firstOrCreate, except for the BelongsToMany relationship. See below:

Being consistent with the rest of the codebase for firstOrCreate/firstOrNew, I went with a union of the attributes and values when creating a model instead of using array_merge (despite the documentation saying otherwise).

{
if (is_null($instance = $this->related->where($attributes)->first())) {
$instance = $this->create($attributes, $joining, $touch);
$instance = $this->create($attributes + $values, $joining, $touch);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why + and not array_merge? (they are not the same!)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@GrahamCampbell I addressed this above

Being consistent with the rest of the codebase for firstOrCreate/firstOrNew, I went with a union of the attributes and values when creating a model instead of using array_merge (despite the documentation saying otherwise).

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.

3 participants
0