draw134
draw134

Reputation: 1187

Laravel Migration Error on foreign key constraint

I have a problem running the migration of my Laravel project. When I run artisan migrate, it stops in the foreign key. Can someone help me with this? I tried the solution on the other similar questions but it does not work.

Error Message: SQLSTATE[HY000]: General error: 1005 Can't create table.

airways.#sql-4588_cfb (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table flights add constraint flights_airport_departure_foreign foreign key (airport_departure) references airports (airport_code) on delete cascade)

flights_table.php

 public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->integer('flight_number')->primary();
            $table->string('airline');
            $table->integer('airport_departure')->unsigned();
            $table->string('departure_time');
            $table->integer('airport_arrival')->unsigned();
            $table->string('arrival_time');
            $table->string('flight_duration');
            $table->timestamps();
        });

        Schema::table('flights', function($table) {
            $table->foreign('airport_departure')
                  ->references('airport_code')->on('airports')
                  ->onDelete('cascade');

                  $table->foreign('airport_arrival')
                  ->references('airport_code')->on('airports')
                  ->onDelete('cascade');
        });
    }


airports_table.php

  public function up()
    {
        Schema::create('airports', function (Blueprint $table) {
            $table->integer('airport_code')->primary();
            $table->string('airport_name');
            $table->string('airport_location');
            $table->string('airport_state');
            $table->timestamps();
        });
    }

Upvotes: 0

Views: 179

Answers (2)

Niko Peltoniemi
Niko Peltoniemi

Reputation: 494

Your foreign key column types are wrong. You're not setting the airport_code as an unsigned integer but airport_departure and airport_arrival are expecting unsigned integers. Also you'll need to create the airports table before creating flights table, not the other way 'round as suggested by others.

Upvotes: 1

salim
salim

Reputation: 11

Rollback your migration, change the order of migration i.e if the airport table is 2014_10_12_0000 and the flights_table is 2014_10_12_00001, change airport table to 0002.

Upvotes: 1

Related Questions