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

Laravel 8 添加外键执行migrate:fresh出现id_rso重复列错误求助

错误成因

你在迁移代码中重复定义了id_rso字段:

  • 第一行$table->unsignedBigInteger('id_rso');已经创建了类型为无符号大整数的id_rso字段
  • 第二行$table->foreignId('id_rso')->constrained('rso');中的foreignId()本身是Laravel提供的语法糖,会自动创建一个unsignedBigInteger类型的同名字段,因此触发了字段重复的报错。
解决方法

两种方案二选一即可:

方案1:保留foreignId写法(推荐,符合Laravel官方编码规范)

删除手动定义unsignedBigInteger的那一行,仅保留foreignId链式调用的代码即可,foreignId会自动完成字段创建+外键关联的逻辑。
修正后的核心代码如下:

public function up()
{   
    Schema::enableForeignKeyConstraints();
    Schema::create('dso', function (Blueprint $table) {
        $table->string('id_dso',30);
        // 删掉原来的unsignedBigInteger行,直接用foreignId
        $table->foreignId('id_rso')->constrained('rso');
        $table->smallInteger('id_focus');
        $table->smallInteger('id_wilayah');
        $table->smallInteger('id_grup_wilayah');
        $table->string('nama_dso',50);
        $table->string('created_by',50)->nullable();
        $table->timestamp('created_date',$precision = 0);
        $table->string('modified_by',50)->nullable();
        $table->timestamp('modified_date',$precision = 0)->nullable()->default(null);
        $table->boolean('status')->default(true);
        $table->timestamps();
        $table->primary('id_dso');
    });
}

方案2:手动拆分字段创建和外键关联逻辑

如果不想使用foreignId语法糖,保留原来的unsignedBigInteger字段定义,将外键关联部分改为普通foreign方法调用即可:

// 保留手动创建字段的代码
$table->unsignedBigInteger('id_rso');
// 改为普通外键定义,不要用foreignId重复创建字段
$table->foreign('id_rso')->references('id')->on('rso');

修改完成后重新执行php artisan migrate:fresh即可正常运行。

内容的提问来源于stack exchange,提问作者Lucas Futami

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:54:03