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

Gorm+MySQL报错Error1075:仅Journal结构体添加Gorm Model时表定义错误

解决GORM添加gorm.Model到Journal结构体时触发的Error 1075错误

错误Error 1075: Incorrect table definition; there can be only one auto column and it must be defined as a key的根源是Journal结构体中Row字段的GORM标签使用错误。

gorm.Model已经内置了自增主键ID字段,而你给Row字段添加的gorm:"foreignKey:category_id"标签属于误用:foreignKey标签是给关联结构体字段(比如Contents里的CategoryModel)用的,用来指定关联依赖的外键字段,不能直接加在普通的数值字段上。这个错误标签会导致GORM生成表结构时逻辑混乱,错误地尝试让Row字段也成为自增列,违反MySQL的单自增列规则。

修正后的Journal结构体

package migrations

import "gorm.io/gorm"

type Journal struct {
   gorm.Model
   ModelName string `gorm:"column:model_name"`
   UpdatedBy string `gorm:"column:updated_by"`
   Row       uint   `gorm:"column:row"` // 移除错误的foreignKey标签
   NewValue  string `gorm:"column:new_value"`
   OldValue  string `gorm:"column:old_value"`
   Column    string `gorm:"column:column"`
}

如果Row字段是用来关联Category表的补充说明

如果你的Row字段原本意图是关联Category表的ID,正确的关联写法应该是:

type Journal struct {
   gorm.Model
   ModelName     string   `gorm:"column:model_name"`
   UpdatedBy     string   `gorm:"column:updated_by"`
   CategoryId    uint     `gorm:"column:category_id"` // 外键字段
   CategoryModel Category `gorm:"foreignKey:CategoryId"` // 在关联字段上指定外键
   NewValue      string   `gorm:"column:new_value"`
   OldValue      string   `gorm:"column:old_value"`
   Column        string   `gorm:"column:column"`
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:45:30