Gorm中结构体字段*gorm.DB调用WithContext方法报错的解决方法
问题解决:Gorm调用WithContext提示未解析引用
可能原因及对应解决方案
1. 使用了Gorm v1版本(github.com/jinzhu/gorm)
Gorm v1中不存在WithContext方法,对应的上下文设置方法是SetContext,修改代码如下:
func (dbStorage DBStorage) PutOrder(order service.Order, ctx context.Context) error { // ... dbStorage.db.SetContext(ctx).Create(&order) // ... }
2. Gorm v2版本但导入路径错误
如果使用的是Gorm v2(gorm.io/gorm),确认导入语句为:
import "gorm.io/gorm"
而非旧版本的github.com/jinzhu/gorm。若存在版本混用,会导致方法找不到的问题。
3. 确认DB字段类型正确性
检查DBStorage结构体的db字段确实是*gorm.DB类型,初始化时确保gorm.Open返回的db指针正确赋值给该字段。
内容的提问来源于stack exchange,提问作者Matthew Kruglikov
相关产品推荐
相关产品推荐

