0

I try to remove a column, which is a foreign key:

$table = $this->table('users');
$table->removeColumn('province_id');
$table->update();

Above gives DB error: The object 'users_province_id' is dependent on column 'province_id'. If I try to remove FK first:

$table = $this->table('users');
$table->removeIndex('province_id');
$table->removeColumn('province_id');
$table->update();

I get the same error. Using removeIndexByName:

$table = $this->table('users');
$table->removeIndexByName('users_province_id');
$table->removeColumn('province_id');
$table->update();

Also doesn't work. Thanks for any help.

ndm
  • 59,784
  • 9
  • 71
  • 110
r34
  • 320
  • 2
  • 12

2 Answers2

1

Your code doesn't remove foreign key constraints, but only indexes and columns. To remove a foreign key constraint, you'd use the dropForeignKey() method, something along the lines of this:

$table = $this->table('users');
$table
    ->dropForeignKey(
        // by columns used in the constraint, this would remove _all_
        // foreign key constraints on the table that are using the
        // `province_id` column
        'province_id',

        // optionally pass the name of the constraint in the second
        // argument instead, in order to remove only a specific single
        // constraint by its name
        'foreign_key_constraint_name'
    )
    ->removeIndex('province_id')
    ->removeColumn('province_id')
    ->update();

See also

ndm
  • 59,784
  • 9
  • 71
  • 110
0

Ok, as someone posted correct answer and than deleted it, I'll post the solution:

Instead of using removeIndex one should use dropForeignKey('province_id').

r34
  • 320
  • 2
  • 12
  • 1
    I deleted it as it was incomplete and I had to check something first. Undeleted now with additional information on how `dropForeignKey()` works. – ndm Aug 20 '20 at 14:33