Laravel 8执行php artisan migrate:fresh报SQLSTATE[42000语法错误如何解决
错误产生原因
- 核心语法错误来自
seller_id字段的类型修饰不合法:unsigned是数值类型(int、bigint等)专属的属性,字符串类型varchar不支持该修饰,迁移代码中$table->string('seller_id',)->unsigned()会生成非法SQL语句,直接触发1064语法错误。 - 迁移代码中
string('status',)、string('image',)、string('seller_id',)存在多余的尾逗号,属于不规范写法,可能引发解析异常。 - 外键字段类型不匹配:Laravel默认生成的users表主键是
bigint unsigned类型,seller_id作为关联外键必须和主键类型保持一致,否则后续外键约束创建也会失败。 - 额外隐藏问题:Product模型中定义的
Product::UNAVAILABLE_PRODUCT值拼写为unavailabel,正确拼写应为unavailable,未修正会导致后续业务逻辑判断异常。
修复方案
- 将
seller_id字段类型修改为和users表主键匹配的unsignedBigInteger,移除错误的string类型+unsigned组合。 - 清除所有string方法中多余的尾逗号。
- 修正Product模型中
UNAVAILABLE_PRODUCT的拼写错误。
修复后完整迁移代码如下:
public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('description',1000); $table->integer('quantity')->unsigned(); $table->string('status')->default(Product::UNAVAILABLE_PRODUCT); $table->string('image')->default(Product::UNAVAILABLE_PRODUCT); $table->unsignedBigInteger('seller_id'); $table->timestamps(); $table->foreign('seller_id')->references('id')->on('users'); }); }
如果你的users表主键为自定义的字符串类型,则把seller_id字段代码修改为$table->string('seller_id');即可,移除unsigned修饰。
修复完成后重新运行php artisan migrate:fresh即可正常执行迁移。
内容的提问来源于stack exchange,提问作者Nesar Ahmad Nori
相关产品推荐
相关产品推荐

