acmestack / gorm-plus

Gorm-plus是基于Gorm的增强版,类似Mybatis-plus语法。Gorm-plus is based on an enhanced version of Gorm, similar to Mybatis-plus syntax.
https://github.com/acmestack/gorm-plus/wiki
Apache License 2.0
285 stars 44 forks source link

事务使用报错 #58

Closed Ls569689934 closed 1 year ago

Ls569689934 commented 1 year ago

下面这样应该也行 // 开启事务 tx := gplus.Begin()

// 使用defer,实现遇到错误时回滚 defer tx.Rollback()

// 新增,传入tx student := Student{Name: "zhangsan", Age: 18, Email: "123@11.com", Birthday: time.Now()} result := gplus.Insert(&student, tx) ...

// 更新,传入tx query, model := gplus.NewQueryStudent query.Eq(&model.Name, "zhangsan").Set(&model.Age, 30) resultDb := gplus.Update[Student](query, tx) ...

// 查询,如果需要在事务中查询,则也需要传入tx resultStudent, db := gplus.SelectById[Student](student.ID, tx) ...

// 提交事务,否则数据库数据不更改 tx.Commit()

按照这个方式传入tx,dao的方法需要一个OptionFunc Cannot use 'tx' (type *gorm.DB) as the type OptionFunc

Ls569689934 commented 1 year ago

// 查询,如果需要在事务中查询,则也需要传入tx resultStudent, db := gplus.SelectById[Student](student.ID, gplus.Db(tx))

yuanfan123 commented 1 year ago

建议到dao.go里面加个这样的事务事项,我也想加入到这个项目开发,不知道有没有交流群 func Tx(txFunc func(tx *gorm.DB) error, opts ...OptionFunc) error { db := getDb(opts...) return db.Transaction(txFunc) }