问题描述
我尝试删除作为外键的列:
$table = $this->table('users');
$table->removeColumn('province_id');
$table->update();
以上给出数据库错误:The object 'users_province_id' is dependent on column 'province_id'
。如果我尝试先删除FK:
$table = $this->table('users');
$table->removeIndex('province_id');
$table->removeColumn('province_id');
$table->update();
我得到同样的错误。使用removeIndexByName
:
$table = $this->table('users');
$table->removeIndexByName('users_province_id');
$table->removeColumn('province_id');
$table->update();
也不起作用。感谢您的帮助。
解决方法
您的代码不会删除外键约束,而只会删除索引和列。要删除外键约束,您可以使用dropForeignKey()
方法,大致方法如下:
$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();
另请参见
,好吧,当有人发布正确答案并删除该答案时,我将发布解决方案:
应该使用removeIndex
而不是使用dropForeignKey('province_id')
。