说人话的 GORM文档 之Context的使用

4 min read

GORM 那傻逼文档真是傻逼妈妈给傻逼儿子开门,傻逼到家了

Context 作用

  1. 持续会话
  2. 设置超时和取消

Context 持续会话

在 GORM 中,持续会话模式通常被用于执行一系列操作。例如,你可以使用 db.WithContext(ctx) 来创建一个新的 *gorm.DB 实例,然后使用这个实例来执行一系列操作

tx := db.WithContext(ctx)
tx.First(&user, 1)
tx.Model(&user).Update("role", "admin")

Context 设置超时

对于长 Sql 查询,你可以传入一个带超时的 context 给 db.WithContext 来设置超时时间,例如:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

db.WithContext(ctx).Find(&users)