I made a bulk update function for use in my Laravel projects. This is much more efficient than most of the features I found on the Internet. This may be useful for those who want to use a batch update request in Laravel. Its first parameter is the table name row, the second is the key name row, based on which you want to update the row or rows, and most of the time it will be "id", and the third parameter is an array of data in the following format
array( array( 'id' => 1, 'col_1_name' => 'col_1_val', 'col_2_name' => 'col_2_val', //... ), array( 'id' => 2, 'col_1_name' => 'col_1_val', 'col_2_name' => 'col_2_val', //... ), //... );
The function will return the number of rows affected. Function Definition:
private function custom_batch_update(string $table_name = '', string $key = '', Array $update_arr = array()) { if(!$table_name || !$key || !$update_arr){ return false; } $update_keys = array_keys($update_arr[0]); $update_keys_count = count($update_keys); for ($i = 0; $i < $update_keys_count; $i++) { $key_name = $update_keys[$i]; if($key === $key_name){ continue; } $when_{$key_name} = $key_name . ' = CASE'; } $length = count($update_arr); $index = 0; $query_str = 'UPDATE ' . $table_name . ' SET '; $when_str = ''; $where_str = ' WHERE ' . $key . ' IN('; while ($index < $length) { $when_str = " WHEN $key = '{$update_arr[$index][$key]}' THEN"; $where_str .= "'{$update_arr[$index][$key]}',"; for ($i = 0; $i < $update_keys_count; $i++) { $key_name = $update_keys[$i]; if($key === $key_name){ continue; } $when_{$key_name} .= $when_str . " '{$update_arr[$index][$key_name]}'"; } $index++; } for ($i = 0; $i < $update_keys_count; $i++) { $key_name = $update_keys[$i]; if($key === $key_name){ continue; } $when_{$key_name} .= ' ELSE ' . $key_name . ' END, '; $query_str .= $when_{$key_name}; } $query_str = rtrim($query_str, ', '); $where_str = rtrim($where_str, ',') . ')'; $query_str .= $where_str; $affected = DB::update($query_str); return $affected; }
It will create and execute the query string as follows:
UPDATE table_name SET col_1_name = CASE WHEN id = '1' THEN 'col_1_value' WHEN id = '2' THEN 'col_1_value' ELSE col_1_name END, col_2_name = CASE WHEN id = '1' THEN 'col_2_value' WHEN id = '2' THEN 'col_2_value' ELSE col_2_name END WHERE id IN('1','2')
source share