5

I added relations to a model. The structure being the following:

A Structure Model hasMany Managers. Each Manager 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.

  • 2
    You asked what I had been searching for a lot of time. – Huzaib Shafi Jul 20 '16 at 16:53
  • You need to save structure model first, then below that use what you have `$structure->managers()->save()` to save your managers. Probably best to wrap it in a transaction so if one fails, the inserts are rolledback. – Andrew Nolan Jul 20 '16 at 17:02
  • 1
    @andrew-nolan I expected something more efficient than `$structure->push()` because saving the relations separately is cumbersome –  Jul 20 '16 at 18:05
  • That's ActiveRecord. You can deal with it or use a tool that suits your needs. – Mateusz Sip Jul 23 '16 at 23:34

1 Answers1

1

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();