The following is just an example:Take the following two models with their relationships
I want to be able to link an address with an user with out directly saving it.
something like:
$user = new User();
$user->name = "John";
$address1 = new Address();
$address1->street = "Foo street";
$address2 = new Address();
$address2->street = "Bar street";
$user->addresses()->push($address1);
$user->addresses()->push($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()
So this different that $user->addresses()->saveMany([$address1, $address2]);
Hope you anyone give me an elegant solution.
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