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

Laravel数据库迁移报错:SQLSTATE[42000]语法错误求助

解决Laravel数据库迁移的1075语法错误

问题场景

执行以下迁移代码时触发数据库错误:

public function up()
{
    Schema::create('subscriptions', function (Blueprint $table) {
        $table->id();
        $table->integer('month',4);
        $table->integer('price',7);
        $table->tinyInteger('status')->default(1);
        $table->timestamps();
    });
}

错误信息

QLSTATE[42000]: 语法错误或访问违规: 1075 表定义不正确; 只能有一个自增列且必须定义为键 (SQL: create table subscriptions (id bigint unsigned not null auto_increment primary key, month int not null auto_increment primary key, price int not null auto_increment primary key, status tinyint not null default '1', created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

错误原因

Laravel的integer()方法第二个参数是布尔值,用于指定字段是否自增,而非字段长度。你传入的4和7会被PHP自动转换为true,导致month和price字段被错误设置为自增主键,与已有的id自增主键冲突,触发MySQL的1075限制(一个表只能有一个自增列)。

修复方案

如果需要设置字段显示长度,使用->length()链式方法;如果不需要限制长度,直接去掉第二个参数即可。修复后的迁移代码如下:

public function up()
{
    Schema::create('subscriptions', function (Blueprint $table) {
        $table->id();
        $table->integer('month')->length(4); // 设置显示长度为4
        $table->integer('price')->length(7); // 设置显示长度为7
        $table->tinyInteger('status')->default(1);
        $table->timestamps();
    });
}

或者,如果你的month字段仅存储1-12的月份值,用更贴合的smallInteger类型更合理:

$table->smallInteger('month'); // SMALLINT类型足够存储1-12的数值
$table->integer('price'); // INT类型默认足够存储常规价格值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:40:35