1

I have to change the type of the user_id column from accounts to nullable, but it's a foreign key with the id column of users, how should it be done correctly?

I'm working with Laravel 5.6.27 and MySQL 5.6, I tried using the functions of the facade, but it did not work. Now I am testing with the statements and I have this error:

In Connection.php line 664: SQLSTATE[HY000]: General error: 1025 Error on rename of './gonano/#sql-c_b' to './gonano/accounts' (errno: 150 - For key constraint is incorrectly formed) (SQL: ALTER TABLE accounts CHANGE user_id user_id INT DEFAULT NULL)

create_users_table:

public function up(): void
{
    Schema::create('users', function (Blueprint $table): void {
        $table->increments('id');
        $table->string('first_name', 100);
        $table->string('last_name', 100);
        $table->string('email')->unique();
        $table->bigInteger('cuit')->unsigned();
        $table->string('password');
        $table->enum('status', ['activated', 'blocked'])->default('activated');
        $table->integer('country_id')->unsigned()->references('id')->on('countries');
        $table->timestampsTz();
    });
}

create_accounts_table:

public function up(): void
{
    Schema::create('accounts', function (Blueprint $table): void {
        $table->bigIncrements('id');
        $table->string('address')->default('');
        $table->integer('user_id')->index()->unsigned();
        $table->integer('system_id')->index()->unsigned()->default(0);
        $table->foreign('user_id')->references('id')->on('users');
        $table->timestampsTz();
    });
}

change_user_id_to_nullable_in_accounts:

public function up()
{
    Schema::disableForeignKeyConstraints();
    DB::table('accounts')->truncate();
    Schema::table('accounts', function (Blueprint $table): void {
        $table->integer('user_id')->nullable()->change();
    });
    Schema::enableForeignKeyConstraints();
}

I need that user_id can be nullable and I can not achieve it, thanks for the help

  • 1
    Possible duplicate of [Migration: Cannot add foreign key constraint in laravel](https://stackoverflow.com/questions/22615926/migration-cannot-add-foreign-key-constraint-in-laravel) – pr1nc3 Jan 24 '19 at 13:20

1 Answers1

1

Create new migration for make nullable to your user_id.

and paste this code in your migration.

public function up()
{
    \Illuminate\Support\Facades\DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    \Illuminate\Support\Facades\DB::table('accounts')->truncate();
    Schema::table('accounts', function (Blueprint $table) {
        $table->integer('user_id')->nullable()->change();
    });
    \Illuminate\Support\Facades\DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Prathamesh Doke
  • 797
  • 2
  • 16
  • 38