Last active
August 29, 2015 14:17
-
-
Save DuffleOne/7233b9b6035e337d68c6 to your computer and use it in GitHub Desktop.
Copy tables, (with changes), from an old table set to a new table set. Uses Laravel atm
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
private function copy($table, $changes = array(), $matches = array(), $ignoreID = true) { | |
if(is_array($table)) { | |
$oldTable = $table[0]; | |
$newTable = $table[1]; | |
} else { | |
$oldTable = $table; | |
$newTable = $table; | |
} | |
$newElements = array(); | |
$oldElements = DB::table($oldTable)->orderBy('id', 'ASC')->get(); | |
$relational = false; | |
foreach($matches as $headKey => $match) { | |
$relational = true; | |
foreach($match as $key => $value) { | |
if($key !== 'matchesOn') { | |
$matches[$headKey][$key] = $this->splitTableCol($value); | |
} else { | |
$matches[$headKey][$key] = $this->splitDot($value); | |
} | |
} | |
} | |
foreach($oldElements as $element) { | |
$insertable = array(); | |
$changedKeys = array(); | |
foreach($element as $key => $value) { | |
$originalKey = $key; | |
if(array_key_exists($key, $changes)) { | |
$key = $changes[$key]; | |
$changedKeys[$originalKey] = $key; | |
} | |
if($ignoreID) { | |
if($key == 'id') { | |
continue; | |
} | |
} | |
foreach($matches as $match) { | |
if($newTable == $match['foreign']['table']) { | |
$oldRecord = DB::table($match['primary']['table'])->where(function($query) use($changedKeys, $element, $match) { | |
$oldKey = array_search($match['foreign']['col'], $changedKeys); | |
$query->where($match['primary']['col'], '=', $element->$oldKey); | |
})->first(); | |
$newRecord = DB::connection('beta')->table($match['primary']['table'])->where(function($query) use($match, $oldRecord) { | |
foreach($match['matchesOn'] as $matchValue) { | |
$query->where($matchValue, '=', $oldRecord->$matchValue); | |
} | |
})->first(); | |
$element->$match['foreign']['col'] = $newRecord->$match['primary']['col']; | |
} | |
} | |
$insertable[$key] = $element->$originalKey; | |
} | |
$newElements[] = $insertable; | |
} | |
DB::connection('beta')->table($oldTable)->truncate(); | |
DB::connection('beta')->table($newTable)->insert($newElements); | |
echo("Copied $table table to the new database.\n"); | |
} | |
private function splitTableCol($name) { | |
$res = explode('.', $name); | |
return array( | |
'table' => $res[0], | |
'col' => $res[1] | |
); | |
} | |
private function splitDot($value) { | |
return explode('.', $value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment