phplaraveldatabasepostgresqldatabase-migration

How ignore foreign key migration in general?


I have a question about migrations in Laravel. Is it possible to handle foreign keys with a simple if statement? Specifically, I want to ensure that if a foreign key already exists, it should not be migrated again. Is there a straightforward way to do this?

This is my code for example.

        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');
            });
        }

Solution

  • I think this will be the straightforward method with an if statement. Here is your updated migration code.

        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');
                }
            });
        }
    

    Just use If(!Schema->hasColumn('table_name', 'column_name'))

    This method has two parameters, hasColumn('table_name', 'column_name')