解决Go gorm踩过的坑

Fiorenza ·
更新时间:2024-09-20
· 1320 次阅读

使用gorm.Model后无法查询数据

Scan error on column index 1, name “created_at”

提示:

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

解决办法:

打开数据库的时候加上parseTime=true

root:123456@tcp(127.0.0.1:3306)/mapdb?charset=utf8&parseTime=true

补充:golang Gorm 的使用总结

建立结构体时可以通过 TableName来指定要查找的表名 func (CoinLog) TableName() string { return "coin_log" } 通过gorm的映射指定对应表的列 ID int64 `gorm:"column:id" json:"id"`

通过预加载可以实现各个模型之间的一对多关系,例如下面的代码,其中device结构体对应多个DeviceModular,DeviceModular又有多个CommWeimaqi

通过下面的查询语句可以查询出对应的相关联数据 db.SqlDB.Preload("DeviceModular", "modular_type=1").Preload("DeviceModular.CommWeimaqi").Find(&device)

gorm暂时不支持批量插入

可以通过下面的方式完成批量插入的功能 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() }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。如有错误或未考虑完全的地方,望不吝赐教。



gorm GO

需要 登录 后方可回复, 如果你还没有账号请 注册新账号