Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
Irman Ahmad Avatar asked Feb 12 '15 02:02

Irman Ahmad


1 Answers

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

like image 67
Edgar Orozco Avatar answered Sep 20 '22 07:09

Edgar Orozco