You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel5.8执行迁移报1005无法创建表外键约束错误如何解决

问题原因

错误的核心诱因是外键字段与关联主键的字段类型不匹配,这是MySQL创建外键约束的硬性要求:

  • users表的usr_id使用bigIncrements('usr_id')定义,实际对应的字段类型是unsigned bigint
  • wallets表的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 21:57:01