-
-
Save AALMA/ad6c629f41931fa2fae78a439ad9446f to your computer and use it in GitHub Desktop.
Mass (bulk) insert or update on duplicate for Laravel 4/5
This file contains hidden or 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
<?php | |
namespace App\Traits; | |
use DB; | |
use Carbon\Carbon; | |
trait MassInsertOrUpdate | |
{ | |
protected $insert_or_update_chunk_size = 1000; | |
public static function insertOrUpdate(array $rows) | |
{ | |
$model = new self(); | |
foreach (array_chunk($rows, $model->insert_or_update_chunk_size, true) as $chunk) { | |
self::insertOrUpdateChunk($chunk); | |
} | |
} | |
protected static function insertOrUpdateChunk(array $rows) | |
{ | |
$model = new self(); | |
$table_prefix = DB::connection($model->connection)->getTablePrefix(); | |
$table = $table_prefix.with($model)->getTable(); | |
self::addTimestampsToRows($rows); | |
$first = reset($rows); | |
$columns = self::extractColumns($first); | |
$values = self::extractValues($rows); | |
$updates = self::extractUpdates($first); | |
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}"; | |
DB::connection($model->connection)->statement($sql); | |
} | |
protected static function addTimestampsToRows(&$rows) | |
{ | |
$model = new self(); | |
if ($model->usesTimestamps()) { | |
$rows = array_map(function ($row) { | |
$row['created_at'] = $row['created_at'] ?? Carbon::now(); | |
$row['updated_at'] = $row['updated_at'] ?? Carbon::now(); | |
return $row; | |
}, $rows); | |
} | |
} | |
protected static function extractUpdates(array $first) | |
{ | |
unset($first['created_at']); | |
return implode(',', array_map(function ($value) { | |
return "$value = VALUES($value)"; | |
}, array_keys($first))); | |
} | |
protected static function extractColumns(array $first) | |
{ | |
return implode(',', array_map(function ($value) { | |
return "$value"; | |
}, array_keys($first))); | |
} | |
protected static function extractValues(array $rows) | |
{ | |
return implode(',', array_map(function ($row) { | |
return '('.implode(',', array_map(function ($value) { | |
return '"'.str_replace('"', '""', $value).'"'; | |
}, $row)).')'; | |
}, $rows)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment