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

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 // indirect
  • gorm.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:00:48