Laravel迁移报错errno:150 外键约束格式错误求助
解决Laravel数据库迁移外键约束错误
错误原因分析
从报错信息和迁移代码来看,存在三个核心问题:
- 表名拼写错误:第二个迁移里外键引用的主表名写成了单数
project_daily_standup_mom,但第一个迁移创建的表是复数project_daily_standup_moms,数据库找不到对应表导致约束失败。 - 字段类型不匹配:Laravel的
$table->id()默认生成bigint unsigned类型主键,但子表中mom_id用的是integer unsigned,类型不一致触发外键约束错误。 - 字段可空性不匹配:外键设置了
onDelete('set null'),但对应的mom_id、task_id字段未添加nullable()属性,删除主表记录时无法将子表字段设为null,违反约束规则。
修正后的第二个迁移文件代码
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateDailyStandupMomListTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('project_daily_standup_mom_lists', function (Blueprint $table) { $table->id(); // 修正字段类型为bigInteger,添加nullable() $table->bigInteger('mom_id')->unsigned()->nullable(); // 修正主表名为复数 $table->foreign('mom_id') ->references('id') ->on('project_daily_standup_moms') ->onDelete('set null') ->onUpdate('cascade'); $table->text('filled_for'); $table->text('remark')->nullable(); $table->text('status'); $table->text('logged_time')->nullable(); $table->text('estimation')->nullable(); $table->text('new_blocker_description')->nullable(); $table->integer('new_blocker_assign_to')->unsigned()->nullable(); $table->foreign('new_blocker_assign_to') ->references('id') ->on('users') ->onDelete('set null') ->onUpdate('cascade'); // 修正task_id添加nullable() $table->integer('task_id')->unsigned()->nullable(); $table->foreign('task_id') ->references('id') ->on('tasks') ->onDelete('set null') ->onUpdate('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('project_daily_standup_mom_lists'); } }
额外建议
如果projects、users表的主键也是bigint类型,第一个迁移文件中的project_id、user_id等字段也建议改为bigInteger,保持类型一致:
// 替换第一个迁移中的integer为bigInteger $table->bigInteger('project_id')->unsigned(); $table->bigInteger('user_id')->unsigned(); $table->bigInteger('edited_by_user')->unsigned()->nullable(); $table->bigInteger('added_by')->unsigned()->nullable();
内容的提问来源于stack exchange,提问作者ZemichaelMD
相关产品推荐
相关产品推荐

