Ad

How To Alter OnDelete('RESTRICT') To CASCADE

- 1 answer

In Laravel 5.8 app I create a migration with table :

{
    Schema::create('reserves', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('storage_space_id')->unsigned()->nullable();
        $table->foreign('storage_space_id')->references('id')->on('storage_spaces')->onDelete('RESTRICT');

        $table->decimal('vat', 12, 2)->nullable();
        ...
        $table->timestamp( 'created_at')->useCurrent();

        $table->index(['storage_space_id', 'reserve_date'], 'reserves_storage_space_id_reserve_date_index');
        $table->index(['storage_space_id', 'reserve_out_date'], 'reserves_storage_space_id_reserve_out_date_index');

    });
}

And now deleting row from storage_spaces I get Integrity constraint violation error when there are related rows in reserves. I know that I need to alter onDelete to “CASCADE”, but I do not can in be done with migration? If yes how?

Thanks!

Ad

Answer

You can create a new migration and then drop the foreign key and recreate it:

Schema::table('reserves', function (Blueprint $table) {
    $table->dropForeign(['storage_space_id']);
    $table->foreign('storage_space_id')
        ->references('id')
        ->on('storage_spaces')
        ->onDelete('cascade');
});

docs

Ad
source: stackoverflow.com
Ad