Laravel 9迁移报错1215:无法添加外键约束求解决
错误信息
1215 Cannot add foreign key constraint (SQL: alter table
company_address_useradd constraintcompany_address_user_user_id_foreignforeign key (user_id) referencesusers(id))
迁移代码
Schema::create('company_address_user', function (Blueprint $table) { $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('company_address_id'); $table->primary(['user_id', 'company_address_id']); }); Schema::table('company_address_user', function (Blueprint $table) { $table->foreign(['user_id'])->references(['id'])->on('users'); $table->foreign(['company_address_id'])->references(['id'])->on('company_addresses'); });
可能的原因及解决办法
迁移顺序错误:
users和company_addresses表必须在company_address_user表之前创建。检查迁移文件的前缀时间戳,确保前两个表的迁移文件时间更早。如果顺序不对,修改文件名的时间前缀,让依赖表先执行迁移。字段类型不匹配:确认
users.id和company_addresses.id的字段类型与中间表的user_id、company_address_id一致。Laravel默认的id()方法是bigIncrements(对应unsignedBigInteger),如果手动修改了主键类型,要保证关联字段类型完全匹配。数据冲突:如果
company_address_user表中已存在数据,且部分user_id或company_address_id在关联表中没有对应记录,添加外键会失败。先清空中间表数据,或者确保所有关联字段的值都在对应表中存在。存储引擎不支持:MySQL的MyISAM引擎不支持外键约束,必须使用InnoDB。确认所有表的存储引擎都是InnoDB,Laravel默认使用InnoDB,若手动修改过,可在迁移中显式指定:
$table->engine = 'InnoDB';
优化后的迁移代码
可以在创建表时直接定义外键,无需分两次操作:
Schema::create('company_address_user', function (Blueprint $table) { $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('company_address_id'); $table->primary(['user_id', 'company_address_id']); $table->foreign('user_id')->references('id')->on('users'); $table->foreign('company_address_id')->references('id')->on('company_addresses'); });
内容的提问来源于stack exchange,提问作者Karthik

