我正在尝试添加一个包含两个外键的表,请参见下文:
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")")
,即使数据库中存在相应的引用表,名称中也没有错字,并且主键/外键的类型匹配。什么会导致此问题?`
这里可能存在一些问题:
尝试拆分迁移。首先创建表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');
});