Last active
January 17, 2017 11:54
-
-
Save IlyaZha/41dc95c2184db5f65695f1092599a5bb to your computer and use it in GitHub Desktop.
Creating and dropping foreign keys
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
/** | |
* Скрипт создания форейн ключа $foreignKey в таблице $table1 на таблицу $table2. | |
* | |
* -Получаем все элементы таблицы1 и таблицы2. | |
* -Перебираем циклом элементы таблицы1 и проверяем существуют ли они в таблице2. | |
* -Если элемент в таблице2 не существует, удаляем ссылку на него из таблицы1. | |
* -Создаем форейн ключ в таблице1. | |
*/ | |
function validateTableAndCreateForeignKey($table1, $table2, $foreignKey) | |
{ | |
$elementsFirstTable = DB::table($table1)->get(); | |
$elementsSecondTable = array_map('keyBy', DB::table($table2)->get()); | |
$deletedKeys = []; | |
foreach ($elementsFirstTable as $element) { | |
if ( | |
array_search($element->$foreignKey, $elementsSecondTable) === false | |
// && !empty($element->$foreignKey) | |
) { | |
$deletedKeys[] = $element->$foreignKey; | |
}; | |
} | |
DB::table($table1) | |
->whereIn($foreignKey, $deletedKeys) | |
->delete(); | |
Schema::table($table1, function (Blueprint $table) use ($table1, $foreignKey) { | |
DB::statement("ALTER TABLE `$table1` CHANGE `$foreignKey` `$foreignKey` INT(10) UNSIGNED NOT NULL;"); | |
}); | |
Schema::table($table1, function (Blueprint $table) use ($foreignKey, $table2) { | |
$table->foreign($foreignKey) | |
->references('id') | |
->on($table2) | |
->onDelete('cascade'); | |
}); | |
} | |
function keyBy($item) | |
{ | |
return $item->id; | |
} |
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
function dropForeignKey($table1, $table2, $foreignKey) | |
{ | |
Schema::table($table1, function (Blueprint $table) use ($table1, $foreignKey) { | |
$table->dropForeign($table1 . '_' . $foreignKey . '_' . 'foreign'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment