arnabrahman's avatar

Altering foreign key for a table in new migration not working

I have a pivot table named 'author_book' & i'm using sqlite

This is the create method of the table

Schema::create('author_book', function (Blueprint $table) {
            $table->integer('author_id')->index();
            $table->integer('book_id')->index();
            $table->timestamps();

            $table->foreign('author_id')
                ->references('id')
                ->on('authors');
            $table->foreign('book_id')
                ->references('id')
                ->on('books');

        });

Now i want to add onDelete('cascade') for those foreign keys. I'm following the solution of Ferid Movsumov - http://stackoverflow.com/questions/26820788/add-on-delete-cascade-to-existing-column-in-laravel Created another migration & added this

Schema::table('author_book', function (Blueprint $table) {
            $table->dropForeign('author_id');
            $table->foreign('author_id')
                ->references('id')
                ->on('authors')
                ->onDelete('cascade');

            $table->dropForeign('book_id');
            $table->foreign('book_id')
                ->references('id')
                ->on('books')
                ->onDelete('cascade');
        });

But nothing has changed, the schema definition of 'author_book' table remains same. What am i doing wrong?

0 likes
5 replies
bobbybouwmann's avatar

You are dropping the wrong key

Schema::table('author_book', function (Blueprint $table) {
    $table->dropForeign('author_book_author_id_foreign');
    $table->foreign('author_id')
        ->references('id')
        ->on('authors')
        ->onDelete('cascade');

    $table->dropForeign('author_book_book_id_foreign');
    $table->foreign('book_id')
        ->references('id')
        ->on('books')
        ->onDelete('cascade');
});

Source: http://laravel.com/docs/5.1/migrations#foreign-key-constraints

arnabrahman's avatar

I've tried dropping the index & it worked.

$table->dropIndex('author_book_author_id_index');

But the same way when i try to drop foreign key nothing changes. SMH

$table->dropForeign('author_book_author_id_foreign');
bobbybouwmann's avatar

Mmh weird stuff.. Did you try to start with an empty sqlite file?

arnabrahman's avatar

Emptied the whole 'author_book' table still didn't work. Manually changed the schema definition in SQLiteStudio.

Please or to participate in this conversation.