我在Laravel项目中遇到迁移问题.
因为我对Laravel相当新,所以我无法理解.
我想将一个外键添加到现有的表中,这样可行,但是当我刷新迁移时,我收到此错误:
[Illuminate\Database\QueryException] sqlSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (sql: drop table `battles`) [PDOException] sqlSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails
这些是我目前的迁移:
表项目
class CreateProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('projects',function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('body'); $table->string('tags'); $table->string('img'); $table->string('img_tricolor'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('projects'); } }
表战
class CreateBattlesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('battles',function (Blueprint $table) { $table->increments('id'); $table->string('battle_theme'); $table->boolean('battle_active'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('battles'); } }
为项目中的战斗添加外键
class AddProjectsBattleIdFk extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('projects',function (Blueprint $table) { $table->integer('battle_id')->unsigned(); $table->foreign('battle_id')->references('id')->on('battles')->onDelete('set null'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('projects',function (Blueprint $table) { // }); } }
我想这与战斗表有关.
解决方法
在down方法中,您需要先删除外键:
在CreateProjectsTable中
public function down() { Schema::table('projects',function (Blueprint $table) { $table->dropForeign('projects_user_id_foreign'); }); Schema::drop('projects'); }
在AddProjectsBattleIdFk中
public function down() { Schema::table('projects',function (Blueprint $table) { $table->dropForeign('projects_battle_id_foreign'); $table->dropColumn('battle_id'); }); }