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

CakePHP 3: can't remove foreign key column using MSSQL driver

我尝试删除一个列,它是一个外键:

$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();

另见

好的,有人 post 编辑了正确的答案而不是将其删除,我将 post 解决方案:

而不是使用 removeIndex 应该使用 dropForeignKey('province_id').