Laravel save Eloquent with relationship

I added a relationship to the model. The structure is as follows:

A Structure hasMany Model Managers . Each Manager hasMany Employees

So, I am doing this using the following code:

 $structure->name = "Something"; $manager1 = new Manager; $manager2 = new Manager; $manager1->name = "Man One"; $manager2->name = "Man Two"; $emp1 = new Employee; $emp2 = new Employee; $emp3 = new Employee; $emp1->name.... ... .... $manager1->add($emp1); $manager1->add($emp2); $manager2->add($emp3); $structure->add($manager1); $structure->add($manager2); .... //Some calculations & necessary processing to fill up other properties of $structure. ///Now I have to save $structure.. $structure->push() 

But it returns an error that $manager requires a foreign key value ( structure_id ) for obvious reasons. $structure->managers()->save() helps, but saves all relationships and their relationships are cumbersome.

Therefore, I need to know a method for saving the entire structure model at once.

+5
source share
1 answer

You can use saveMany (you need to pass an array of the Manager object):

 $structure->managers()->saveMany(array($managers)); 

Or (you need to pass an array of arrays with object data declared in $ fillable array in the Manager model):

 $structure->managers()->createMany(array($managersData)); $structure->save(); 
0
source

All Articles