Answer the question
In order to leave comments, you need to log in
Laravel how to create two related models at once?
Hello, tell me please! Using orm, I want to create two interconnected models at once, so far the code looks like this, but it seems to me that this is not correct, it can probably be done with one request, tell me at least where to dig. Thank you.
$user = new User; // id|space_id|name
$space = new Space; // id|user_id
$user->name = $name;
$user->save();
$space->user_id = $user->id;
$space->save();
$user = User::find($user->id);
$user->space_id = $space->id;
$user->save();
Answer the question
In order to leave comments, you need to log in
Since you have data denormalization, you can’t get away from triple saving.
Are you sure that you need this denormalization, did you do it consciously?
If you store references to another entity in both models simply out of ignorance, then do not do this and the problem will not arise. I would store a link to the User in Space and that's it, because, most likely, there can't be a Space without a User, but quite the contrary.
If you have correctly specified links in your models, you can rewrite it like this, but the general meaning will not change from this:
$user = new User; // id|space_id|name
$space = new Space; // id|user_id
$user->name = $name;
$user->save();
$space->user->associate($user);
$space->save();
$user->space->associate($space);
$user->save();
In the User model:
public function space()
{
return $this->hasOne('App\Space');
}
+ in migrations you specify connections.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question