When I'm trying to set a foreign key constraint in laravel 5 with migrations I receive the error:
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
rittenregistratie
add co nstraint rittenregistratie_karakterrit_id_foreign foreign key (karakterrit_id
) referenceskarakterrit
(id
) on delete cascade) [PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint D:\wamp\www>
But I have now idea why??? The order of migrating is right so why do I receive this error? The table rittenregistratie has a foreign key called karakterrit_id this is the primary key in the table karakterrit.
This is my migration rittenregistratie:
public function up()
{
Schema::create('rittenregistratie', function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->timestamps('datum');
$table->integer('beginstand');
$table->integer('eindstand');
$table->text('van');
$table->text('naar');
$table->text('bezoekadres');
$table->text('geredenroute');
$table->integer('karakterrit_id')->default(1);
$table->text('toelichting');
$table->integer('kilometerszakelijk');
$table->integer('kilomteresprive');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('karakterrit_id')
->references('id')
->on('karakterrit')
->onDelete('cascade');
});
}
Add
Have you created the
users
Table andkarakterrit
that you used in your query. If you have both tables, check the creation date of the migration files they both should be created before other table that references them.Another problem might be
MyISAM
which does not support. Instead use InnoDBfor the most of the case the referenced column must be either primary key or have unique key from my findings