I'm trying to add foreign key in my table exam:
public function up()
{
Schema::create('exams', function (Blueprint $table) {
$table->id();
$table->BigInteger('student_id')->unsigned()->nullable();
$table->BigInteger('subject_id')->unsigned()->nullable();
$table->integer('mark');
$table->timestamps();
$table->foreign('student_id')
->references('id')
->on('students');
$table->foreign('subject_id')
->references('id')
->on('subjects');
});
}
Student's table:
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('fname');
$table->string('mname');
$table->string('lname');
$table->timestamps();
});
}
Subject's table:
Schema::create('subjects', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
I have searched a lot and try it with unsignedBigInteger
or $table->bigInteger('student_id')->unsigned()->nullable();
and try this:
Laravel migration: "Foreign key constraint is incorrectly formed" (errno 150)
But this error is still happening when I use php artisan migrate
What can i do?
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1005 Can't create table
salamstu
.exams
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tableexams
add constraintexams_student_id_foreign
foreign key (student_id
) referencesstudents
(id
) on delete cascade)at C:\Users\User\Documents\laravel\SalamStu\vendor\laravel\framework\src\Illuminate\Database\Connection.php:716 712▕ // If an exception occurs when attempting to run a query, we'll format the error 713▕ // message to include the bindings with SQL, which will make this exception a 714▕ // lot more helpful to the developer instead of just the database's errors. 715▕ catch (Exception $e) { ➜ 716▕ throw new QueryException( 717▕ $query, $this->prepareBindings($bindings), $e 718▕ ); 719▕ } 720▕ }
1
C:\Users\User\Documents\laravel\SalamStu\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create tablesalamstu
.exams
(errno: 150 "Foreign key constraint is incorrectly formed")")2
C:\Users\User\Documents\laravel\SalamStu\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501 PDOStatement::execute()