Schema::create('students', function (Blueprint $table) {
$table->id();
$table->integer('age')->unsigned();
$table->integer('city_id')->unsigned();
$table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->text('name');
$table->timestamps();
});
i'm new laravel, when i run migrate, in terminal show
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table students add constraint students_city_id_foreign foreign key (city_id) references cities (id) on delete cascade)
help me fix
CodePudding user response:
Your problem is on the order of the code. You want to make a foreign key to a table which is not yet exists.
Try this instead:
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->integer('age')->unsigned();
$table->integer('city_id')->unsigned();
$table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->text('name');
$table->timestamps();
});
Schema::table('students', function(Blueprint $table) {
$table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
});
Like this, you first creates both tables, and after that you set the foreign key.
CodePudding user response:
If you are using more recent version of Laravel id fields are now unsignedBigInteger field. So you should do something like:
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->text('name');
$table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->integer('age')->unsigned();
$table->foreignId('city_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
Also, make sure the cities migration is running before students.
CodePudding user response:
=>your cities migration first create then after students migration create because your city_id foreign key reference to the cities table laravel migration check order and order wise migration run so first cities migration run(cities table create) then students migration run.
