Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

The following is just an example:Take the following two models with their relationships

  • User => hasMany('Address', 'user_id')
  • Address => => belongsTo('User', 'user_id')

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.

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.

© 2025 Laravel.io - All rights reserved.