You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When seeding data with a factory that implements a Belongs To relation to another entity we sometimes encounter a situation where we would like to create the entity belong to any, random parent.
For example, in case of the Users/Posts example from the Laravel documentation.
Assume we have already created Users in a previous steps, and all Users are available in $users (for example $users = User:all() or via output from a different factory).
Now, I want to create X number of Posts and have them assigned to distinct users, but I don't really care which.
Currently, to achieve the above we have to do some work arounds, for example
Looping around: We can loop over $users and create Posts inside this loop and assign them to the current loop's user.
Manually setting parent_id: Using state we can "manually" set user_id as state works with sequences. But this code can get really messy and unintuitive, especially when using polymorphic relations.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Problem description:
When seeding data with a factory that implements a Belongs To relation to another entity we sometimes encounter a situation where we would like to create the entity belong to any, random parent.
For example, in case of the Users/Posts example from the Laravel documentation.
Assume we have already created Users in a previous steps, and all Users are available in
$users
(for example$users = User:all()
or via output from a different factory).Now, I want to create X number of Posts and have them assigned to distinct users, but I don't really care which.
Proposed solutions:
Work arounds:
Currently, to achieve the above we have to do some work arounds, for example
$users
and create Posts inside this loop and assign them to the current loop's user.parent_id
: Usingstate
we can "manually" setuser_id
asstate
works with sequences. But this code can get really messy and unintuitive, especially when using polymorphic relations.Beta Was this translation helpful? Give feedback.
All reactions