Problem with referential integrity in migrations (Laravel 5)

1

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

  

[Illuminate \ Database \ QueryException]
  SQLSTATE [HY000]: General error: 1215 Can not 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 Can not add foreign key constraint

If I change the set null by cascade it works.

I'm creating the 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');
            });
    
asked by anonymous 30.11.2016 / 16:59

1 answer

1

On this line

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

add nullable() :

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

response obtained in the question SOEn - Laravel Schema onDelete set null na response .

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

    
02.12.2016 / 00:07