Laravel Eloquent - 保存/更新相关的一对多关系数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28468502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:54:33  来源:igfitidea点击:

Laravel Eloquent - Save/Update Related One-To-Many Relationship Data

phplaraveleloquentrelationship

提问by Irman Ahmad

I have an entity Set that has many Items in it. So, when updating the sets, the form includes the field to update it's item too. I've done it and it's working well, but I'm not sure if it's the correct and most efficient/elegant way to do it. Here's my code:

我有一个实体集,里面有很多项目。因此,在更新集合时,表单也包含用于更新其项目的字段。我已经完成并且运行良好,但我不确定这是否是正确和最有效/最优雅的方式。这是我的代码:

        $set->fill(Input::all());

        foreach (Input::get('course') as $course_id => $content) {
            $item = $set->items->filter(function ($item) use ($course_id) {
                return ($item->course_id == $course_id);
            })->first();
            $item->content = $content;
            $set->items()->save($item);
        }
        $set->save();

As you can see, for each items, I looped through all the input (which may vary on how many it has), filter it, and save the value 1 by 1. So a query is executed for every iteration. I use filter so that it doesn't have to do a query for every check.

如您所见,对于每个项目,我循环遍历所有输入(可能因输入的数量而异),对其进行过滤,然后将值 1 x 1 保存。因此,每次迭代都会执行一个查询。我使用过滤器,这样它就不必对每次检查都进行查询。

So my question is, is there a more efficient/elegant way to do this? Something like saveMany() maybe?

所以我的问题是,有没有更有效/更优雅的方法来做到这一点?像 saveMany() 之类的东西?

采纳答案by Edgar Orozco

You can use the method saveManylike this:

您可以像这样使用saveMany方法:

        $set->fill(Input::all());
        $items = array();
        foreach (Input::get('course') as $course_id => $content) {
            $item = $set->items->filter(function ($item) use ($course_id) {
                return ($item->course_id == $course_id);
            })->first();
            $item->content = $content;
            $items[] = $item;
        }

        $set->items()->saveMany($items);
        $set->save();

As pointed in related models of laravel docs

正如laravel 文档的相关模型中所指出的