如何解决SQLSTATE [HY000]:常规错误:1215无法添加外键约束无法将外键添加到具有现有数据的表中
我没有走运就搜索了所有内容,并不断收到此错误消息。我检查了两个表,所有数据类型都匹配,并且创建了索引。任何帮助,将不胜感激!这是我正在使用的语句:
DB::statement(
"ALTER TABLE `customers`
ADD CONSTRAINT `customers_lang_code_foreign`
FOREIGN KEY (`lang_code`)
REFERENCES `languages` (`iso_code`)
ON DELETE RESTRICT
ON UPDATE CASCADE;"
);
编辑:这些都是我得到的错误:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: ALTER TABLE `customers`
ADD CONSTRAINT `customers_lang_code_foreign`
FOREIGN KEY (`lang_code`)
REFERENCES `languages` (`iso_code`)
ON DELETE RESTRICT
ON UPDATE CASCADE;)
at /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query,we'll format the error
661| // message to include the bindings with SQL,which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query,$this->prepareBindings($bindings),$e
666| );
667| }
668|
Exception trace:
1 Doctrine\DBAL\Driver\PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
/home/vagrant/code/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119
2 PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
/home/vagrant/code/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117
Please use the argument -v to see more details.
解决方法
可能有几个原因,我猜列类型不匹配。检查this article了解更多想法。
,您不能在要添加约束的列中具有现有数据的表上添加FK约束。 您必须先删除数据,然后再添加约束,然后重新对表进行水合。
您还可以禁用外键检查:
SET FOREIGN_KEY_CHECKS = 0;
//ALTER TABLE ...
SET FOREIGN_KEY_CHECKS = 1;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。