Multiple record update with same array $key=>$value?
I have an array where keys are the id's of the records I need to edit, and values are, well, the value to change in the database for selected column.
I saw a function that did exactly this in eloquent a while ago but I can't remember what it is and I couldn't find it online too. Anyone know something that does this or should I use the spaghetti code below? I don't think that's very efficient.
public function order_photos(Request $request)
{
$data = $request->input('photo_order');
foreach ($data as $key=>$value){
$image = EstatesPhoto::find($key);
$image->photo_order = $value;
$image->save()
}
return back();
}
@tisuchi Almost does, but ->update(['photo_order' => $values]) part tries to insert the whole array value into an integer column I guess, because all records come out 0 after the code runs.
Any idea how can I fix that? I think I'm gonna need that foreach loop anyway to get the value with $data['id'] unless there's a magic method for that but it doesn't seem likely...
@tisuchi
Here's a sample return case for the array. As I said in the post, keys are the ids of records that needs to update and values are the values to update on photo_order column. So whereIn part works perfectly with ids being in the $ids array, but giving $values as a single value in the update breaks the logic here since every id relates to a single value.
@Sinnbeck Yeah I was looking up that mavinoo package just now. Although, there'll be a maximum of 40 records that'll be updated this way. Would it really be a problem to use foreach? I'm using a shared hosting nothing powerful but still..
I also found something like this ;
#To get a performance improve, you can use a transaction. This way database wont commit after every single update, wich makes the process considerably faster.
DB::beginTransaction();
// your loop and updates;
if( !$user )
{
rollbackTransaction();
} else {
// Else commit the queries
commitTransaction();
}