一般如何忽略外键迁移?

问题描述 投票:0回答:1

我有一个关于 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 database postgresql database-migration
1个回答
0
投票

我相信是的,但是用 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['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');
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.