Solve the pit that go Gorm stepped on

Time:2021-10-18

Data cannot be queried after gorm.model is used

Scan error on column index 1, name “created_at”

Tips:

Scan error on column index 1, name “created_at”: unsupported Scan, storing driver.Value type []uint8

terms of settlement:

Add parsetime = true when opening the database


root:[email protected](127.0.0.1:3306)/mapdb?charset=utf8&parseTime=true

Supplement: Usage Summary of golang Gorm

When creating a structure, you can specify the table name to be searched through tablename


func (CoinLog) TableName() string {
 return "coin_log"
}

Specify the columns of the corresponding table through the mapping of Gorm


ID            int64              `gorm:"column:id" json:"id"`

The one to many relationship between various models can be realized through preloading. For example, the following code, in which the device structure corresponds to multiple devicemodules, and the devicemodule has multiple commweimaqi

The corresponding associated data can be queried through the following query statement


db.SqlDB.Preload("DeviceModular", "modular_type=1").Preload("DeviceModular.CommWeimaqi").Find(&device)

Gorm does not support batch insertion for the time being

Batch insertion can be completed in the following ways


  tx := db.SqlDB.Begin()
  sqlStr := "INSERT INTO report_form (id,create_time,choose_count, device_fall_count,game_order_count,coin_count,member_count," +
   "day_member_count,visit_count,lgz_coin_count,weimaqi_coin_count,store_id,real_coin_count,m_coin_count,coin_spec) VALUES "
  vals := []interface{}{}
  const rowSQL = "(?,?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)"
  var inserts []string
  for _, elem := range reportForms {
   inserts = append(inserts, rowSQL)
   vals = append(vals, elem.ID, elem.CreateTime, elem.ChooseCount, elem.DeviceFallCount, elem.GameOrderCount, elem.CoinCount, elem.MemberCount, elem.DayMemberCount, elem.VisitCount, elem.LgzCoinCount, elem.WeimaqiCoinCount, elem.StoreId, elem.RealCoinCount, elem.MCoinCount, elem.CoinSpec)
  }
  sqlStr = sqlStr + strings.Join(inserts, ",")
  err := tx.Exec(sqlStr, vals...).Error
  if  err != nil {
   tx.Rollback()
   fmt.Print(err)
  }else {
   tx.Commit()
  }

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.