【问题标题】:Laravel throws errno: 150 "Foreign key constraint is incorrectly formed" despite the correct syntaxLaravel 抛出 errno:150 “外键约束的格式不正确”,尽管语法正确
【发布时间】:2020-08-12 03:45:06
【问题描述】:

我正在尝试添加一个包含两个外键的表,见下文:

Schema::create('semester_cohorts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('semester_id');
        $table->unsignedBigInteger('cohort_id');
        $table->timestamps();

        $table->foreign('semester_id')
            ->references('semesters')
            ->on('id')
            ->onDelete('cascade');

        $table->foreign('cohort_id')
            ->references('id')
            ->on('cohorts')
            ->onDelete('cascade');
    });

我收到以下消息:PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table [table name](errno: 150 "Foreign key constraint is incorrectly formed")"),尽管数据库中存在相应的引用表,但名称中没有拼写错误,并且主键/外键的类型匹配。什么可能导致这个问题? `

【问题讨论】:

    标签: php mysql laravel database-migration laravel-migrations


    【解决方案1】:

    您的第一个外键中混淆了referenceson

    $table->foreign('semester_id')
                ->references('semesters')
                ->on('id')
                ->onDelete('cascade');
    

    应该是

    $table->foreign('semester_id')
                ->references('id')
                ->on('semesters')
                ->onDelete('cascade');
    

    【讨论】:

      【解决方案2】:

      这里可能有一些问题:

      • 检查两个表的列类型,类型应该相同
      • 尝试拆分迁移。首先创建表 semester_cohorts 然后在下面使用

        Schema::table('semester_cohorts', function (Blueprint $table) {
           $table->foreign('semester_id')
                ->references('id')
                ->on('semesters')
                ->onDelete('cascade');
        
            $table->foreign('cohort_id')
                ->references('id')
                ->on('cohorts')
                ->onDelete('cascade');
        });
        

      【讨论】:

        【解决方案3】:

        我实际上遇到了这个问题,这是因为unsignedBigInteger 类型。

        外键列必须与其引用的主键具有相同的数据类型。

        因此,如果您在semesterscohorts 表中的主键bigIncrements 类型的

        您应该将外键类型定义为BigInteger,然后在其后面加上unsigned()

          $table->bigIncrements('id');
            $table->bigInteger('semester_id')->unsigned();
            $table->bigInteger('cohort_id')->unsigned();
            $table->timestamps();
        

        编辑:

        就像kerbholz说你在定义外键时有一个错误

        【讨论】:

        • 这两个表中的主键都是 unsignedBigInteger(或者,确切地说是返回 unsignedBigInteger 的 bigIncrements)
        猜你喜欢
        • 2017-04-13
        • 2019-09-17
        • 2020-12-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 2017-05-29
        • 2018-06-19
        相关资源
        最近更新 更多