简体   繁体   中英

Laravel save Eloquent along with relationships

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM