【问题标题】:Laravel save Eloquent along with relationshipsLaravel 保存 Eloquent 和关系
【发布时间】:2016-07-20 16:52:27
【问题描述】:

我向模型添加了关系。结构如下:

A Structure 型号 hasMany Managers。每个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


【解决方案1】:

您可以使用 saveMany(您必须传递一个 Manager 对象数组):

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

或者(您必须传递一个数组数组,其中包含在 Manager 模型的 $fillable 数组中声明的对象数据):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多