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

Laravel迁移报错1075:表定义错误,自增列需唯一且设为键

解决Laravel迁移中的SQLSTATE[42000]: 1075错误

哇,这个错误我之前也踩过坑!咱们直接看问题根源:你不小心在同一个表中定义了两个自增列,这违反了MySQL的规则——一个表只能有一个自增列,而且它必须是主键。

先看你的迁移代码里的问题行:

public function up() { 
    Schema::create('posts', function (Blueprint $table) { 
        $table->increments('id'); // 这里已经是自增主键了
        $table->bigInteger('post_author', 20); // 就是这行出问题!
        $table->text('post_title'); 
        $table->longText('post_content'); 
        $table->string('post_status', 20); 
        $table->string('comment_status', 20); 
        $table->string('post_type', 20); 
        $table->timestamps(); 
        $table->softDeletes(); 
    }); 
}

Laravel的bigInteger方法第二个参数不是字段长度,而是是否设置自增(布尔值)。你传的20会被PHP自动转成true,结果post_author就被误设成自增列了,和已经存在的id自增列冲突,直接触发了1075错误。

怎么修复?

把post_author的定义改成正确的写法就行,分两种情况:

情况1:只是想设置字段长度

用length()链式调用指定长度:

$table->bigInteger('post_author')->length(20);

情况2:推荐用法(作者ID通常关联用户表,用无符号大整数)

如果这个字段是关联users表的id,更建议用无符号大整数,还可以顺便加外键约束保证数据完整性:

$table->unsignedBigInteger('post_author');
// 可选:添加外键关联,删除用户时同步删除其发布的文章
$table->foreign('post_author')
      ->references('id')
      ->on('users')
      ->onDelete('cascade');

修改完之后,重新跑迁移命令:

php artisan migrate

这次就能顺利创建posts表啦!

内容的提问来源于stack exchange,提问作者Anwarul Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:31:17