CakePHP 3:无法使用MSSQL驱动程序删除外键列

问题描述

我尝试删除作为外键的列:

$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')

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...