Problem with referential integrity in Migrations (Laravel 5)

Asked

Viewed 373 times

1

I’m having a problem using onDelete('set null') in a foreign key. You are returning the error:

[Illuminate Database Queryexception]
SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint (SQL: alter table users add Constraint users_instituicoes_id_foreign Foreign key (instituicoes_id) References instituicoes (id) on delete set null)

[Pdoexception]
SQLSTATE[HY000]: General error: 1215 Cannot add Foreign key Constraint

If I change the set null for cascade works.

I’m creating Migration like this:

       Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('nome');
                $table->string('user')->unique();
                $table->string('email')->unique();
                $table->string('password');
                $table->integer('instituicoes_id')->unsigned();
                $table->string('telefone')->nullable();
                $table->string('img')->default('default.png');
                $table->boolean('ativo');
                $table->rememberToken();
                $table->timestamps();

            });
            Schema::table('users', function(Blueprint $table){
                $table->foreign('instituicoes_id')
                      ->references('id')
                      ->on('instituicoes')
                      ->onDelete('set null');
            });

1 answer

1

Along those lines

$table->integer('instituicoes_id')->unsigned();

add nullable():

$table->integer('instituicoes_id')->unsigned()->nullable();

answer obtained in the question Soen - Laravel Schema onDelete set null in reply.

After this adjustment you can rotate the part $table->foreign with ->onDelete('SET NULL') that will work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.