Reputation: 401
I am trying to add a table containing two foreign keys, see below:
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');
});
I get the following message: PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table [table name](errno: 150 "Foreign key constraint is incorrectly formed")")
, even though the respective referenced tables exist in the database, there are no typos in names and the types of primary/foreign keys match. What could cause this problem?
`
Upvotes: 0
Views: 52
Reputation: 1433
I actually had this issue and its because of the type unsignedBigInteger
.
Foreign key column must be the same data type as the primary key it references.
So if your primary key in semesters
& cohorts
table is of type bigIncrements
you should define the Foreign key type as BigInteger
then follow it with an unsigned()
:
$table->bigIncrements('id');
$table->bigInteger('semester_id')->unsigned();
$table->bigInteger('cohort_id')->unsigned();
$table->timestamps();
Edit:
Like kerbholz said you have an error in defining the foreign keys
Upvotes: 0
Reputation: 1360
There are some problems possible here:
Try to split migrations. Firstly create table semester_cohorts then below use
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');
});
Upvotes: 1
Reputation:
You got references
and on
mixed up in your first foreign key:
$table->foreign('semester_id')
->references('semesters')
->on('id')
->onDelete('cascade');
should be
$table->foreign('semester_id')
->references('id')
->on('semesters')
->onDelete('cascade');
Upvotes: 4