Laravel5.8执行迁移报1005无法创建表外键约束错误如何解决
问题原因
错误的核心诱因是外键字段与关联主键的字段类型不匹配,这是MySQL创建外键约束的硬性要求:
users表的usr_id使用bigIncrements('usr_id')定义,实际对应的字段类型是unsigned bigintwallets表的id使用bigIncrements('id')定义,实际对应的字段类型也是unsigned bigint- 你在
user_wallet_transactions表中定义的user_id、wallet_id都是unsignedSmallInteger,对应字段类型为unsigned smallint,和关联的主键类型完全不一致,因此触发报错。
解决方法
修改user_wallet_transactions迁移文件中两个外键字段的定义,调整为和关联主键一致的unsignedBigInteger类型即可:
public function up() { Schema::create('user_wallet_transactions', function (Blueprint $table) { $table->bigIncrements('id'); // 替换原unsignedSmallInteger为unsignedBigInteger $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('usr_id')->on('users'); // 替换原unsignedSmallInteger为unsignedBigInteger $table->unsignedBigInteger('wallet_id'); $table->foreign('wallet_id')->references('id')->on('wallets'); $table->string('amount'); $table->string('description'); $table->timestamps(); }); }
如果修改后仍有报错,可额外排查迁移执行顺序:需保证users表、wallets表的迁移文件创建时间早于user_wallet_transactions表的迁移文件,避免关联表未提前创建导致的外键错误。
内容的提问来源于stack exchange,提问作者user16333885
相关产品推荐
相关产品推荐

