I have a User
model, which has a one-to-many relationship with UserEvent
s. So, each User
can have many UserEvent
s.
When I create a new User
, I need to also create a new "sign up" event for them, which would be an instance of UserEvent
. I would like to be able to create this event through a method on my User
object, and for this event to be automatically saved and associated when I call save
on the new User
object.
somewhere in my controller:
// Creates the new User
$user = new User();
// Creates a new sign-up event for the User
$user->newEventSignUp();
// Saves the new user, associating and saving the sign-up event at the same time
$user->save();
According to this question, I could implement my newEventSignUp
like so:
public function newEventSignUp(){
$event = new UserEvent([
"event_type" => "sign_up",
"description" => $description
]);
$this->events->add($event);
return $event;
}
And then call push
rather than save
on $user
to push the newly associated events. However, I am told that the call to $this->events
in newEventSignUp
will trigger an additional query, impacting performance.
My other idea is to simply store all new UserEvent
objects created by my newEvent*
methods in an array in User
, and then overload User::save()
to associate and save the newly added events in my array. However, that doesn't quite feel correct either.
Which approach should I use?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire