Laravel抛出错误号:150“尽管正确的语法,外键约束的格式也不正确”

问题描述 投票:0回答:1

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

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个回答
0
投票

这里可能存在一些问题:

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

    Schema::table('semester_cohorts', function (Blueprint $table) {
       $table->foreign('semester_id')
            ->references('semesters')
            ->on('id')
            ->onDelete('cascade');
    
        $table->foreign('cohort_id')
            ->references('id')
            ->on('cohorts')
            ->onDelete('cascade');
    });
    
© www.soinside.com 2019 - 2024. All rights reserved.