2014-12-19 44 views
0

當我使用遷移警予顯示此錯誤添加此外鍵:錯誤,當我添加外鍵警予

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 ; 

請幫我。

+0

請將英文顯示爲法文錯誤。它可以幫助更快地獲得答案。 – 2014-12-19 08:52:09

+0

no this english – user3231235 2014-12-20 18:21:57

回答

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」的表,而不是你的PHP代碼所說的「newspaper」表。

此外,將外鍵約束添加到的表在您的PHP代碼中稱爲「materiallll」,在執行的SQL中稱爲「材質」。

Here's對Yii addForeignKey()函數的使用的引用,以及here's對提供正確ADD FK語句的帖子的引用。