【发布时间】:2016-07-20 16:52:27
【问题描述】:
我向模型添加了关系。结构如下:
A
Structure型号hasManyManagers。每个ManagerhasManyEmployees
所以我使用以下代码完成了这项工作:
$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()
但它返回一个错误,$manager 出于显而易见的原因需要外键值 (structure_id)。 $structure->managers()->save() 确实有帮助,但保存所有关系及其关系很麻烦。
因此我需要知道一次保存整个结构模型的方法。
【问题讨论】:
-
你问我一直在寻找什么。
-
您需要先保存结构模型,然后在下面使用您拥有的
$structure->managers()->save()来保存您的经理。可能最好将其包装在事务中,因此如果失败,则插入回滚。 -
@andrew-nolan 我希望比
$structure->push()更有效,因为单独保存关系很麻烦 -
那是 ActiveRecord。您可以处理它或使用适合您需求的工具。
标签: php laravel laravel-5 eloquent