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(idbigint unsigned not null auto_increment primary key,monthint not null auto_increment primary key,priceint not null auto_increment primary key,statustinyint not null default '1',created_attimestamp null,updated_attimestamp 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
相关产品推荐
相关产品推荐

