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;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...