我在yii中添加外键时出错

时间:2014-12-19 07:30:21

标签: php mysql yii migrate

当我使用migrate yii添加此外键时显示此错误:

add foreign key fk_material_userprofile: material (insert_user_ID) references userprofile (userID) 
...exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: 
SQLSTATE[HY000]: General error: 1215 Impossible d'ajouter des contraintes d'index externe. The SQL 
statement executed was: ALTER TABLE `material` ADD CONSTRAINT `fk_material_userprofile` FOREIGN KEY 
(`insert_user_ID`) REFERENCES `userprofile` (`userID`) ON DELETE CASCADE ON UPDATE RESTRICT' in 
E:\framework\db\CDbCommand.php:358

这是我的代码:

public function up()
{
    $this->addForeignKey("fk_newspaper", "materiallll", "newspaper_ID", "newspaper", "newspaper_ID", "CASCADE", "RESTRICT");
}

这是我的数据库:

CREATE TABLE IF NOT EXISTS `materiallll` (
`material_ID` int(11) NOT NULL AUTO_INCREMENT,
`newspaper_ID` tinyint(4) NOT NULL,
PRIMARY KEY (`material_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
请帮助我。

1 个答案:

答案 0 :(得分:0)

您可以看到正在执行的SQL语句:

ALTER TABLE `material` ADD CONSTRAINT `fk_material_userprofile` FOREIGN KEY 
(`insert_user_ID`) REFERENCES `userprofile` (`userID`) ON DELETE CASCADE ON UPDATE RESTRICT'

您可以看到它与您提供的PHP代码无关:

public function up()
{
$this->addForeignKey("fk_newspaper", "materiallll", "newspaper_ID", "newspaper", "newspaper_ID",          "CASCADE", "RESTRICT");
}

所以,看起来你得到的错误是关于你正在创建的其他一些约束,它被命名为" fk_material_userprofile"并引用一个名为" userprofile"的表,而不是一个名为" newspaper"的表。正如你的PHP代码所说的那样。

此外,将添加外键约束的表称为" materiallll"在你的PHP代码中它被称为'材料'在执行的SQL中。

Here's对Yii addForeignKey()函数的使用的引用,以及here's对提供正确的ADD FK语句的帖子的引用。