|
<?php |
|
|
|
/** |
|
* Created by PhpStorm. |
|
* User: hafiq |
|
* Date: 03/11/2019 |
|
* Time: 11:36 PM |
|
*/ |
|
|
|
use Illuminate\Support\Facades\Schema; |
|
use Illuminate\Database\Schema\Blueprint; |
|
use Illuminate\Database\Migrations\Migration; |
|
|
|
class AlterAllTableId extends Migration |
|
{ |
|
/** |
|
* Run the migrations. |
|
* |
|
* @return void |
|
*/ |
|
public function up() |
|
{ |
|
$this->upDown(true); |
|
} |
|
|
|
/** |
|
* Reverse the migrations. |
|
* |
|
* @return void |
|
*/ |
|
public function down() |
|
{ |
|
$this->upDown(false); |
|
} |
|
|
|
private function upDown($isUp = true) |
|
{ |
|
$connection = Schema::getConnection(); |
|
|
|
$connection->transaction(function($connection) use ($isUp) { |
|
$manager = $connection->getDoctrineSchemaManager(); |
|
$tables = $manager->listTableNames(); // get all existing tables |
|
|
|
$listForeignKeys = []; |
|
|
|
|
|
\Log::info("drop"); |
|
foreach ($tables as $current) { |
|
Schema::table($current, function (Blueprint $table) use ($manager, &$listForeignKeys) { |
|
// get all existing foreign keys object in each table |
|
foreach ($manager->listTableForeignKeys($table->getTable()) as $foreignKey) { |
|
// store in array |
|
$listForeignKeys[$table->getTable()][] = $foreignKey; |
|
// drop foreign related bcoz of cannot change the datatype |
|
$table->dropForeign($foreignKey->getLocalColumns()); |
|
} |
|
}); |
|
} |
|
|
|
\Log::info("change"); |
|
foreach ($tables as $current) { |
|
Schema::table($current, function (Blueprint $table) use ($manager, $isUp) { |
|
$map = collect($manager->listTableColumns($table->getTable()))->keys()->toArray(); |
|
if (in_array('id', $map)) { |
|
if ($isUp) { |
|
$table->bigIncrements('id')->change(); |
|
} else { |
|
$table->increments('id')->change(); |
|
} |
|
} |
|
}); |
|
} |
|
|
|
\Log::info("foreign"); |
|
foreach ($listForeignKeys as $key => $listForeignKey) { |
|
Schema::table($key, function (Blueprint $table) use ($listForeignKey, $isUp) { |
|
foreach ($listForeignKey as $foreign) { |
|
if ($isUp) { |
|
$table->unsignedBigInteger($foreign->getLocalColumns()[0])->change(); |
|
} else { |
|
$table->unsignedInteger($foreign->getLocalColumns()[0])->change(); |
|
} |
|
|
|
$definition = $table->foreign($foreign->getLocalColumns()[0]) |
|
->references($foreign->getForeignColumns()) |
|
->on($foreign->getForeignTableName()); |
|
foreach ($foreign->getOptions() as $index => $option) { |
|
if ($option && $index == 'onDelete') { |
|
$definition = $definition->onDelete($option); |
|
} |
|
|
|
if ($option && $index == 'onUpdate') { |
|
$definition = $definition->onUpdate($option); |
|
} |
|
} |
|
} |
|
}); |
|
} |
|
}); |
|
} |
|
} |