无法在*gorm.db上使用WithContext(ctx)方法,而不是gorm.db。

huangapple go评论94阅读模式
英文:

Can't use WithContext(ctx) method on *gorm.db instead of gorm.db

问题

我将为您翻译以下内容:

我将我的数据库初始化为一个结构体

type DBStorage struct {
   db *gorm.DB
}

使用以下代码进行初始化:

db, err := gorm.Open("postgres", DatabaseURL)
...
return &DBStorage{
   db: db,
}

一切都正常工作:查询、更新和其他所有操作。但是当我尝试在项目中添加上下文时,它就不起作用了:

func (dbStorage DBStorage) PutOrder(order service.Order, ctx context.Context) error {
...
   dbStorage.db.WithContext(ctx).Create(&order)
...
}

它显示WithContext是一个未解析的引用。而dbStorage.db.Create(&order)却可以正常工作。我该如何解决这个问题?

我尝试了一些愚蠢的事情,比如从结构体中删除*,但这会破坏封装的整体思想。我还尝试阅读了https://gorm.io/docs/method_chaining.html,但不知道如何实现它,也不知道它是否适用于我的情况。如果它适用的话,我想请您解释一下。

英文:

I initialize my db as a struct

type DBStorage struct {
   db *gorm.DB
}

with

db, err := gorm.Open("postgres", DatabaseURL)
...
return &DBStorage{
   db: db,
}

Everything works fine: queries, updates, and all other operations. But then I tried to add Contexts to my project it didn't work like that:

func (dbStorage DBStorage) PutOrder(order service.Order, ctx context.Context) error {
...
   dbStorage.db.WithContext(ctx).Create(&order)
...
}

It says that WithContext is an unresolved reference. While dbStorage.db.Create(&order) works fine. How should I fix this?

I tried some silly things like removing * from the struct, but it kinda breaks the whole incapsulation idea. Also tried reading https://gorm.io/docs/method_chaining.html but didn't get how to implement it and if it is a solution for my case. If it is, I ask for some clarification.

答案1

得分: 1

请检查你的导入语句。应该使用import gorm.io/gorm而不是import github.com/jinzhu/gorm

该库的第一个版本是github.com/jinzhu/gorm,其中gorm.DB类型没有WithContext()方法。

GORM V2 迁移到了 https://github.com/go-gorm/gorm,并且导入路径为gorm.io/gorm。版本2添加了DB.WithContext()方法。

英文:

Check your import statement. It should be import gorm.io/gorm instead of import github.com/jinzhu/gorm.

The first version of the library is github.com/jinzhu/gorm where the gorm.DB type has no WithContext() method.

GORM V2 moved to https://github.com/go-gorm/gorm and has import path gorm.io/gorm. Version 2 added the DB.WithContext() method.

huangapple
  • 本文由 发表于 2022年10月31日 03:58:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/74256334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定