Laravel Eloquent - Save / Update Related Data for One-to-Many

I have a set of objects in which there are many elements. Thus, when updating sets, the form includes a field for updating it. I did it and it works well, but I'm not sure if this is the right and efficient / elegant way to do it. Here is 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 element I scrolled through all the input data (which may differ from their number), filter it and save the value 1 by 1. Thus, the query is executed for each iteration. I use a filter so that it does not execute a query for each check.

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

+5
source share
1 answer

You can use the saveMany method as follows:

  $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 stated in related laravel docs models

+3
source

Source: https://habr.com/ru/post/1213196/


All Articles