У меня вопрос о миграции в Laravel. Можно ли обрабатывать внешние ключи с помощью простого оператора if? В частности, я хочу гарантировать, что если внешний ключ уже существует, его не следует переносить снова. Есть ли простой способ сделать это?
Это мой код, например.
if (Schema::connection('orders_import')->hasTable('mymuesli_label')) {
Schema::connection('orders_import')->table('mymuesli_label', function (Blueprint $table) {
$table->foreign(['roll'], 'roll_id')->references(['id'])->on('mymuesli_roll');
});
}
if (Schema::connection('orders_import')->hasTable('parameter_mapping')) {
Schema::connection('orders_import')->table('parameter_mapping', function (Blueprint $table) {
$table->foreign(['customer'], 'parameter_mapping_fk_customer')->references(['id_customer'])->on('customer');
});
}
if (Schema::connection('orders_import')->hasTable('product_mapping')) {
Schema::connection('orders_import')->table('product_mapping', function (Blueprint $table) {
$table->foreign(['customer'], 'product_mapping_fk_customer')->references(['id_customer'])->on('customer');
});
}
🤔 А знаете ли вы, что...
PHP обладает хорошей производительностью благодаря опкодированию.
Думаю, да, но с laravel 11. С Schema::getForeignKeys('your_table'). Я приведу пример для вашего первого кода:
use Illuminate\Support\Facades\Schema;
$foreignKeys = Schema::connection('orders_import')->getForeignKeys('mymuesli_label');
$foreignKeyExists = false;
foreach ($foreignKeys as $foreignKey) {
if ($foreignKey['name'] === 'roll_id') {
$foreignKeyExists = true;
break;
}
}
if (!$foreignKeyExists) {
Schema::connection('orders_import')->table('mymuesli_label', function (Blueprint $table) {
$table->foreign(['roll'], 'roll_id')->references(['id'])->on('mymuesli_roll');
});
}
// Then set the $foreignKeyExists to false and keep with the search on your tables.
PS: Этот метод дает вам массив массивов с name
(строка) и columns
(массив строк), и вам нужно правильно выполнить миграцию ->foreign($columns, $name)
.
Я думаю, что это будет простой метод с оператором if. Вот ваш обновленный код миграции.
if (Schema::connection('orders_import')->hasTable('parameter_mapping')) {
Schema::connection('orders_import')->table('parameter_mapping', function (Blueprint $table) {
if (!Schema::hasColumn('parameter_mapping','parameter_mapping_fk_customer')) {
$table->foreign(['customer'], 'parameter_mapping_fk_customer')->references(['id_customer'])->on('customer');
}
});
}
if (Schema::connection('orders_import')->hasTable('product_mapping')) {
Schema::connection('orders_import')->table('product_mapping', function (Blueprint $table) {
if (!Schema::hasColumn('product_mapping','product_mapping_fk_customer')) {
$table->foreign(['customer'], 'product_mapping_fk_customer')->references(['id_customer'])->on('customer');
}
});
}
Просто используйте If(!Schema->hasColumn('table_name', 'column_name'))
Этот метод имеет два параметра: hasColumn('table_name', 'column_name')