Last active
April 12, 2024 16:54
-
-
Save RuGa/5354e44883c7651fd15c to your computer and use it in GitHub Desktop.
Mass (bulk) insert or update on duplicate for Laravel 4/5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Mass (bulk) insert or update on duplicate for Laravel 4/5 | |
* | |
* insertOrUpdate([ | |
* ['id'=>1,'value'=>10], | |
* ['id'=>2,'value'=>60] | |
* ]); | |
* | |
* | |
* @param array $rows | |
*/ | |
function insertOrUpdate(array $rows){ | |
$table = \DB::getTablePrefix().with(new self)->getTable(); | |
$first = reset($rows); | |
$columns = implode( ',', | |
array_map( function( $value ) { return "$value"; } , array_keys($first) ) | |
); | |
$values = implode( ',', array_map( function( $row ) { | |
return '('.implode( ',', | |
array_map( function( $value ) { return '"'.str_replace('"', '""', $value).'"'; } , $row ) | |
).')'; | |
} , $rows ) | |
); | |
$updates = implode( ',', | |
array_map( function( $value ) { return "$value = VALUES($value)"; } , array_keys($first) ) | |
); | |
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}"; | |
return \DB::statement( $sql ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
does this work without composite keys ? I want to mass update but it requires me 7 composite keys to detect duplicate due to extremely poor constructed data from amazon api.