jeudi 1 août 2019

Set a foreign key column to nullable in migration

I'm trying to update a foreign key column and set it to nullable in Laravel migration.

CreateArtTable migration:

public function up()
{
    Schema::create('art', function (Blueprint $table) {
        $table->bigIncrements('id')->unsigned();
        $table->bigInteger('item_id')->unsigned()->comment('ItemID');
        $table->foreign('item_id')->references('id')->on('items');
    });
}

public function down()
{
    Schema::dropIfExists('art');
}

Since this is already live and we're doing some updates, we're doing our best not to touch the existing migration files. And here's what I do:

ChangeArticleTableAddNullablesToItemId migration:

   Schema::table('art', function (Blueprint $table) {
       $table->dropForeign('art_item_id_foreign');
       $table->integer('item_id')->nullable()->unsigned()->change();
       $table->foreign('item_id')->references('id')->on('users');
   });

Now when I run php artisan:migrate refresh --seed it returns an error:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1832 Cannot change column 'item_id': used in a foreign key constraint 'art_item_id_foreign' (SQL: ALTER TABLE art CHANGE item_id item_id INT UNSIGNED DEFAULT NULL COMMENT 'ItemID')

How could I set the foreign key to nullable in migration?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire