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

Laravel 8执行php artisan migrate:fresh报SQLSTATE[42000语法错误如何解决

错误产生原因
  1. 核心语法错误来自seller_id字段的类型修饰不合法:unsigned是数值类型(int、bigint等)专属的属性,字符串类型varchar不支持该修饰,迁移代码中$table->string('seller_id',)->unsigned()会生成非法SQL语句,直接触发1064语法错误。
  2. 迁移代码中string('status',)、string('image',)、string('seller_id',)存在多余的尾逗号,属于不规范写法,可能引发解析异常。
  3. 外键字段类型不匹配:Laravel默认生成的users表主键是bigint unsigned类型,seller_id作为关联外键必须和主键类型保持一致,否则后续外键约束创建也会失败。
  4. 额外隐藏问题:Product模型中定义的Product::UNAVAILABLE_PRODUCT值拼写为unavailabel,正确拼写应为unavailable,未修正会导致后续业务逻辑判断异常。
修复方案
  1. 将seller_id字段类型修改为和users表主键匹配的unsignedBigInteger,移除错误的string类型+unsigned组合。
  2. 清除所有string方法中多余的尾逗号。
  3. 修正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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:48:02