Hi,
I think you may be loonking for the associate
method. ( ~> http://laravel.com/docs/4.2/eloquent#inserting-related-models (Associating Models (Belongs To))
It works like you did, except you don't save it to database.
$user = new User();
$address1 = new Address();
$address2 = new Address();
$user->addresses()->associate($address1);
$user->addresses()->associate($address2);
//do some stuff to maybe validate some things or pass the user object to some other controllers that handels it
//Save the user and the addresses here.
$user->save();
Oeps! I was asking the question for the wrong relationship. I'm sorry @maximeguerreiro. I've update my post. I know the associate function works for the "belongs to" relationship, but is there something similar for a "has many" relationship. I hope you have a solution for that :).
I have no clue. I would rather think that ->addresses()->push(..)
would link it, without setting the parent_id
. But if it's not the case, I don't know.
The following code inserts the records in the database, but the webserver responds with a 502 afterwards:
$user = new User();
$user->save();
$address1 = new Address();
$address1->user()->associate($user);
$user->addresses[] = $address1;
$address2 = new Address();
$address2->user()->associate($user);
$user->addresses[] = $address2;
$user->push();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community