Search code examples
phpmysqllaravel-5artisan-migrate

General error: 1215 Cannot add foreign key constraint on tables


I have been trying out all possible solutions based on other stack questions and answers but I'm still not getting any success so I had to make my own question.

I have the following Schemas

Schema::create('file_data', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');

......

        Schema::create('claims', function (Blueprint $table) {
            $table->engine = 'InnoDB';
         ....
            $table->integer('file_id')->unsigned()->nullable()->default(DB::raw('NULL'));

          ....
            $table->foreign('budget_id')
                ->references('id')
                ->on('budgets')
                ->onDelete('cascade');

        });

        Schema::create('claims_details', function (Blueprint $table) {
            $table->engine = 'InnoDB';
           .........
            $table->integer('file_id')->unsigned()->nullable()->default(DB::raw('NULL'));
          ..........

        });

In another file

Schema::table('claims', function(Blueprint $table){
        $table->foreign('file_id')
            ->references('id')
            ->on('file_data')
            ->onDelete('cascade');
      });

      Schema::table('claims_details', function(Blueprint $table){
        $table->index(['invoice_date','claim_id']);
        $table->foreign('claim_id')
            ->references('id')
            ->on('claims')
            ->onDelete('cascade');
            $table->foreign('file_id')
                ->references('id')
                ->on('file_data');
      });

when I run the command php artisan migrate I get the following error

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table claims add constraint claims_file_id_ foreign foreign key (file_id) references file_data (id) on delete cascade)

  • The tables are Innob
  • The columns are of the same type
  • the columns are unsigned
  • the files run in the correct order
  • The only difference is that file_id needs to be null( they have to be)

Is it because the column is "null" makes it fail? I tried it without it being null and still failed. What are other causes that can cause it to have this issue?


Solution

  • Turns out I needed to have the columns indexed