Mentenyia
Mentenyia

Reputation: 211

Laravel 5.2 drop foreign key

Good day,

I am trying to drop a foreign key in a Laravel 5.2 migration previously implemented like this:

EDIT: The creation of the id in the table (before using foreign key on it) was:

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

The foreign key:

Schema::table('agents', function (Blueprint $table){
        $table->foreign('agent_rights_id')->references('id')->on('agent_rights');
    });

My drop looks like this:

 Schema::table('agents', function (Blueprint $table){
        $table->dropForeign('agents_agent_rights_id_foreign');
        $table->dropColumn('agent_rights_id');
    });

I found out, that one must take the "real" index name and not the label - this I have already thought of in the previous snippet (as a reference to this question).

But this gives me the errors:

[Illuminate\Database\QueryException]                                                                                                                                                                                          
SQLSTATE[HY000]: General error: 1025 Error on rename of './{name}/agents' to './{name}/#sql2-2a6-1d8' (errno: 152) (SQL: alter table `agents` drop foreign key `agents_agent_rights_id_foreign`)  



[PDOException]                                                                                                                                  
SQLSTATE[HY000]: General error: 1025 Error on rename of './{name}/agents' to './{name}/#sql2-2a6-1d8' (errno: 152) 

Researching this brings up no real solutions, only bug messages from MySQL...

Question: Do you guys anything about this, or what was wrong with my snippet?

Upvotes: 0

Views: 3409

Answers (1)

Manish
Manish

Reputation: 3633

@Mentenyia This is compulsory for using unsigned() before creating Foreign key constraint. Please read the link https://laravel3.veliovgroup.com/docs/database/schema#foreign-keys .

Note: The field referenced in the foreign key is very likely an auto increment and therefore automatically an unsigned integer. Please make sure to create the foreign key field with unsigned() as both fields have to be the exact same type, the engine on both tables has to be set to InnoDB, and the referenced table must be created before the table with the foreign key.

So you should have to create like this:

$table->integer('agent_rights_id')->unsigned(); // Always create column before creating Foreign key constraint otherwise this will also give error.
$table->foreign('agent_rights_id')->references('id')->on('agent_rights');

After when you will be going to delete Foreign key No issue/ error will arise.

For droping Indexing Use this method table-name_column-name_index-type

$table->dropForeign('agents_agent_rights_id_foreign');

Upvotes: 3

Related Questions