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

时间:2022-04-12 20:17:38

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×1。所以每次迭代都会执行一个查询。我使用过滤器,这样它就不必对每个检查进行查询了。

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

我的问题是,有没有更高效/优雅的方法来做这个?也许像saveMany()?

1 个解决方案

#1


4  

You can use the method saveMany like 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文档的相关模型所示

#1


4  

You can use the method saveMany like 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文档的相关模型所示