在 yii 中添加外键时出错


Error when i add foreign key in yii

当我使用迁移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 ;

请帮帮我。

您可以看到正在执行的 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"的表,而不是您的PHP代码所说的名为"报纸"的表。

此外,外键约束将被添加到的表在 PHP 代码中称为"materiallll",在执行的 SQL 中称为"material"。

这是对 Yii addForeignKey(( 函数用法的引用,这里是对给出正确 ADD FK 语句的帖子的引用。