Reputation:
I added relations to a model. The structure being the following:
A
Structure
ModelhasMany
Managers
. EachManager
hasMany
Employees
So I get this done 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
needs value of foreign key (structure_id
) for obvious reasons. $structure->managers()->save()
does help but saving all the relations and their relations is cumbersome.
Hence I need to know the method of saving the whole structure model at once.
Upvotes: 5
Views: 1731
Reputation: 29
You can use saveMany (you have to pass an array of Manager object):
$structure->managers()->saveMany(array($managers));
Or (you have to pass an array of arrays with object data declared in the $fillable array in the Manager model):
$structure->managers()->createMany(array($managersData));
$structure->save();
Upvotes: 1