-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
[11.x] Add pending attributes to child models #53677
base: 11.x
Are you sure you want to change the base?
Conversation
@tontonsb thanks for the PR. One potential inconsistency to surface... We have this method: public function withPivotValue($column, $value = null); It works very similar to this method you have proposed; however, it also sets a "where" clause on the pivot table in addition to putting the specified value on any newly created pivot models. I'm wondering if this method you're proposing should also set |
@taylorotwell that would make this even more convenient for my usecases. I was going to use it with a corresponding Should I also change the method to support an equivalent API? I.e. /**
* @param string|\Illuminate\Contracts\Database\Query\Expression|array<string, string> $column
* @param mixed $value
*/
public function withAttribute($column, $value = null); I'm now wondering whether I should investigate if this can be done on the Builder itself. I don't need it at the moment, but being able to not only |
@tontonsb yeah a similar API might be nice, in addition to |
@taylorotwell I added there By trying it out in an actual project, I noticed that relations created using |
See #53720 for a simpler implementation (without manual handling in |
Problem
Currently a relationship like this:
Allows you to query
$parent->children()->get()
as well as create related models$parent->children()->create()
that can be queried by the former$parent->children()->get()
.Meanwhile a scoped relationship like this:
Allows you to query for active records
$parent->children()->get()
, but doing$parent->children()->create()
will insert an inactive (with the default value ofactive
to be precise) child and$parent->children()->get()
will not return what you just inserted.Solution
I propose adding "pending attributes" on relationships to allow specifying additional attributes that should be applied when creating new models. In theory this would allow setting any attributes on the newly created related models, but in particular this would allow solving the above issue like this:
And with such setup
$parent->children()->create()
will create an activeChildModel
.The pending attributes serve as defaults that can be overriden: