Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

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();
Last updated 2 years ago.
0

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 :).

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

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();
Last updated 2 years ago.
0

Does anyone else have a good solution?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

boedy boedy Joined 19 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.