如何使用CDbMigration从表中删除密钥

时间:2013-10-24 14:29:07

标签: php mysql yii foreign-keys database-migration

这是我桌子的结构:

CREATE TABLE `company_info` (
  `id` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_polish_ci DEFAULT NULL,
  `description` longtext COLLATE utf8_polish_ci,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `created_info` date DEFAULT NULL,
 `company_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Index_1` (`id`),
 KEY `FK_Reference_4` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci

我需要在Yii 1.x中使用CDbMigration来更改它。目前,密钥FK_Reference_4company_id)是表idcompany的外键。我想:

  • 删除旧的外键,
  • 将新的一个添加到另一个表(users)。

当我尝试使用yiic migration执行迁移时,命令失败:

$this->dropForeignKey('FK_Reference_4','company_info');

有以下错误:

Exception: CDbCommand failed to execute the SQL
statement: SQLSTATE[HY000]: General error: 1025 Error on rename of '.\focuserv\
company_info' to '.\focuserv\#sql2-1b0-18' (errno: 152). The SQL statement execu
ted was: ALTER TABLE `company_info` DROP FOREIGN KEY `FK_Reference_4` (E:\IDEs\w
amp\www\focuserv\focuserv\framework\db\CDbCommand.php:358)

所以dropForeignKey失败了。我该如何解决或解决这个问题?

1 个答案:

答案 0 :(得分:2)

基于上面的create table sql语句,它看起来不像你的FK_Reference_4是外键,它看起来像普通索引。尝试更改

$this->dropForeignKey('FK_Reference_4','company_info');

$this->dropIndex('FK_Reference_4','company_info');

FYI外键sql语句如下所示:

ALTER TABLE `company_info` 
ADD CONSTRAINT `FK_Reference_4` FOREIGN KEY (`company_id`) 
REFERENCES `company` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;