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] Set relation parent key when using forceCreate on HasOne and HasMany relations #42280

Closed
wants to merge 1 commit into from

Conversation

rodrigopedra
Copy link
Contributor

Closes #42273

As explained in issue #42273 when calling several methods that either create or instantiate a related instance from a relation method, the relation parent's key is automatically filled, but not when calling forceCreate.

Take this model as an example:

class Lesson extends Model
{
    public function questions()
    {
        return $this->hasMany(Question::class);
    }
}

When calling all these following methods the lesson primary key is set as the new question instance foreign key automatically:

$lesson = Lesson::first();

$q1 = $lesson->questions()->create(...);
$q2 = $lesson->questions()->findOrNew(...);
$q3 = $lesson->questions()->firstOrNew(...);
$q4 = $lesson->questions()->make(...);
$q5 = $lesson->questions()->save(new Question(...));

This behavior is also present in other methods which use the ones listed above such as updateOrCreate, saveMany, and others.

But when calling ->forceCreate(...) from a relation, the foreign key is not set, which I agree with issue's #42273 OP, that is not the expected behavior.

Reason it does not work as the other is due to forceCreate not being implemented on HasOneOrMany, thus it is deferred to the underlying Builder which, of course, would not set any additional attributes.

This PR:

  • Adds a forceCreate method to the HasOneOrMany relation class, which adds the relation parent key before actually force creating a related instance
  • Adds relevant tests

@driesvints
Copy link
Member

@rodrigopedra is this also present in 8.x? If so we'll need to direct the PR there.

@rodrigopedra
Copy link
Contributor Author

@driesvints it is.

But as I considered it not to be a bug, but an improvement over an expected behavior I thought it would not fit the 8.x branch anymore.

But I can redirect it to 8.x if you think it is fine.

@rodrigopedra
Copy link
Contributor Author

@driesvints as I will be out for some hours, I sent PR #42281 targeted to the 8.x branch. Please close the one you think should be closed. Thanks =)

@driesvints
Copy link
Member

Thanks @rodrigopedra

@driesvints driesvints closed this May 6, 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.

ForceCreate through relationship
2 participants