简体   繁体   中英

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

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.

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

You can use the method saveMany like this:

        $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

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