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 constraintclaims_file_id_ foreign
foreign key (file_id
) referencesfile_data
(id
) on delete cascade)
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?
Turns out I needed to have the columns indexed