Skip to content

Instantly share code, notes, and snippets.

@VadimGut
Last active February 7, 2019 08:03
Show Gist options
  • Save VadimGut/672da182921f70dfcea972e207e86676 to your computer and use it in GitHub Desktop.
Save VadimGut/672da182921f70dfcea972e207e86676 to your computer and use it in GitHub Desktop.
Laravel 5 - insert on duplicate key update helper
if (!function_exists('insertOnDuplicateKeyUpdate')) {
/**
* @param \Illuminate\Database\Query\Builder $builder
* @param array $values
* @param array $exclude_columns_from_updating - this columns from being updated (they will still be inserted)
*
* @return int
*/
function insertOnDuplicateKeyUpdate(Illuminate\Database\Query\Builder $builder, array $values, array $exclude_columns_from_updating = [])
{
if (empty($values)) {
return 0;
}
// Case where $data is not an array of arrays.
if (!isset($values[0])) {
$values = [$values];
}
// find the key columns
list($first_row) = $values;
if (empty($exclude_columns_from_updating)) {
$update_columns = array_keys($first_row);
} else {
$update_columns = array_diff(array_keys($first_row), $exclude_columns_from_updating);
}
// Build sql query
$grammar = $builder->getGrammar();
$sql = $grammar->compileInsert($builder, $values);
$sql .= ' ON DUPLICATE KEY UPDATE ';
$sql .= implode(',', array_map(function ($val) {
return sprintf('`%s` = VALUES(`%s`)', $val, $val);
}, $update_columns));
// Build the bindings of the values
// later to be used in the statement
$bindings = [];
foreach ($values as $record) {
foreach ($record as $value) {
$bindings[] = $value;
}
}
return $builder->getConnection()->affectingStatement($sql, $bindings);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment