【问题标题】:Error when i add foreign key in yii在 yii 中添加外键时出错
【发布时间】:2014-12-19 07:30:20
【问题描述】:

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

请帮帮我。

【问题讨论】:

  • 请将法语显示的错误翻译成英语。它可以帮助更快地获得答案。

标签: php mysql yii migrate


【解决方案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”的表,而不是一个名为“newspaper”的表作为您的 PHP 代码说。

此外,将添加外键约束的表在您的 PHP 代码中称为“materialllll”,在执行的 SQL 中称为“material”。

Here's 引用了 Yii addForeignKey() 函数的使用,here's 引用了给出正确 ADD FK 语句的帖子。

【讨论】:

    猜你喜欢
    • 2014-02-12
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多