Laravel cannot add foreign key constraint

2019-08-15 00:10发布

问题:

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

回答1:

Add

$table->integer('karakterrit_id')->unsigned()->default(1);

Have you created the users Table and karakterrit 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 InnoDB

DB::statement('ALTER TABLE categories ENGINE = InnoDB');


回答2:

for the most of the case the referenced column must be either primary key or have unique key from my findings



标签: php laravel-5