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

Laravel 6执行php artisan migrate时SQL语法错误求助

解决Laravel迁移时的SQL 1064语法错误

嘿,我帮你拆解下这个问题,你遇到的报错主要来自两个明显的问题:

错误原因1:unsigned修饰符用错了字段类型

unsigned是专门给数值类型字段(比如int、bigint、decimal)设计的修饰符,绝对不能用在string类型字段上。你看迁移代码里的id_Supplier、id_DeviceType、id_DeviceBrand都是string类型,却加了unsigned,这在MariaDB/MySQL里属于语法违规,直接触发了1064错误。

错误原因2:重复定义了字段

你还不小心重复定义了device_name字段——既有$table->string('device_name');又有$table->mediumText('device_name');,这会导致生成的SQL里出现两个同名字段,后续执行肯定也会出问题。

修正后的迁移代码

根据常见的外键关联场景,我给你调整了代码:

public function up() {
    Schema::create('transaction_ins', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('idTransactionIN');
        $table->date('buy_date');
        // 假设关联表的主键是unsigned bigint类型,这里用unsignedBigInteger匹配类型
        $table->unsignedBigInteger('id_Supplier');
        $table->unsignedBigInteger('id_DeviceType');
        $table->unsignedBigInteger('id_DeviceBrand');
        // 保留一个合适类型的device_name字段,这里选string,你可以根据需求改成mediumText
        $table->string('device_name');
        $table->decimal('device_price', 11, 2);
        $table->integer('amount');
        $table->decimal('sum_price', 15, 2);
        $table->mediumText('context');
        $table->timestamps();

        // 外键约束逻辑保持不变
        $table->foreign('id_Supplier')
              ->references('idSupplier')
              ->on('suppliers')
              ->onUpdate('cascade');
        $table->foreign('id_DeviceType')
              ->references('idDeviceType')
              ->on('device_types')
              ->onUpdate('cascade');
        $table->foreign('id_DeviceBrand')
              ->references('idDevicebrand')
              ->on('device_brands')
              ->onUpdate('cascade');
    });
}

额外提醒

  • 如果你的关联表(比如suppliers)的主键是string类型,那只需要把外键字段改成$table->string('id_Supplier');(去掉unsigned)就行,不用改成unsignedBigInteger。
  • 一定要确保外键字段的类型和关联表主键的类型完全一致,不然会触发外键约束不匹配的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:22:10