Im having trouble creating a transaction using golang gorm orm. I am getting field index out of range error. Cant seem to understand the problem here. I am running the transaction in manual mode.
in go.mod file
gorm.io/driver/mysql v1.3.6 // indirect
gorm.io/gorm v1.23.8 //indirect
My Models are
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"`
}
now in my code:
ownerID := 1
db := GetDB() //returns *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) //prints the id perfectly
company_user := &models.CompanyUser{
UserID: ownerID,
CompanyID: company.ID,
}
tx = tx.Create(company_user) // <= this line panics
if tx.Error != nil {
tx.Rollback()
return tx.Error
}
result := tx.Commit()
if result.Error != nil {
tx.Rollback()
return tx.Error
}
The weird part is if i duplicate this line tx = tx.Create(company) multiple times inside this transaction and comment out the tx = tx.Create(company_user) line, then the transaction works perfectly. It inserts multiple company model without any complain.
If I do the same with only tx = tx.Create(company_user) line (with hard coded value), it is successful in creating multiple company_user model without any complain.
But when I am using both tx = tx.Create(company) and tx = tx.Create(company_user) together inside this transaction, it gives error: reflect: Field index out of range
gorm config used while initializing db connection:
&gorm.Config{
SkipDefaultTransaction: true,
PrepareStmt: true,
}