我有一个关于 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');
});
}
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['columns'] === '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');
});
}