GORM手动事务执行时触发reflect: Field index out of range错误求助
GORM手动事务执行时触发"reflect: Field index out of range" panic
我在使用Golang的GORM ORM执行手动事务时遇到问题,触发了reflect: Field index out of range的panic,无法定位原因。
依赖版本
go.mod中的依赖版本:
gorm.io/driver/mysql v1.3.6 // indirectgorm.io/gorm v1.23.8 // indirect
模型定义
type Company struct { ID uint64 `json:"id"` Name string `gorm:"size:255;not null" json:"name"` OwnerID uint64 `gorm:"not null" json:"owner_id"` CreatedAt *time.Time `gorm:"autoCreateTime" json:"created_at,omitempty"` UpdatedAt *time.Time `gorm:"autoUpdateTime" json:"updated_at,omitempty"` } type CompanyUser struct { ID uint64 `json:"id"` UserID uint64 `gorm:"not null" json:"user_id"` CompanyID uint64 `gorm:"not null" json:"company_id"` CreatedAt *time.Time `gorm:"autoCreateTime" json:"created_at,omitempty"` UpdatedAt *time.Time `gorm:"autoUpdateTime" json:"updated_at,omitempty"` }
事务代码逻辑
ownerID := 1 db := GetDB() // 返回*gorm.DB tx := db.Begin() company := &models.Company{ OwnerID: ownerID, Name: "Lorem Ipsum", } tx = tx.Create(company) if tx.Error != nil { tx.Rollback() return tx.Error } fmt.Println(company.ID) // 能正常打印出ID company_user := &models.CompanyUser{ UserID: ownerID, CompanyID: company.ID, } tx = tx.Create(company_user) // <= 此行触发panic if tx.Error != nil { tx.Rollback() return tx.Error } result := tx.Commit() if result.Error != nil { tx.Rollback() return tx.Error }
异常现象
- 如果在事务中多次执行
tx = tx.Create(company)并注释掉tx = tx.Create(company_user),事务能正常执行,可插入多条Company数据; - 如果仅执行
tx = tx.Create(company_user)(使用硬编码值),也能成功插入多条CompanyUser数据; - 但同时执行两者时,就会出现
reflect: Field index out of range错误。
数据库初始化的GORM配置
&gorm.Config{ SkipDefaultTransaction: true, PrepareStmt: true, }
内容的提问来源于stack exchange,提问作者Noob Coder
相关产品推荐
相关产品推荐

