package model import ( "context" "git.noahlan.cn/northlan/ntools-go/gorm-zero/gormc" "gorm.io/gorm" ) var _ GiftModel = (*customGiftModel)(nil) type ( // GiftModel is an interface to be customized, add more methods here, // and implement the added methods in customGiftModel. GiftModel interface { giftModel // Transaction 开启事务,传入方法即可 Transaction(ctx context.Context, tx *gorm.DB, fn func(tx *gorm.DB) error) error // InsertTx 事务插入 InsertTx(ctx context.Context, tx *gorm.DB, data *Gift) error // UpdateTx 事务更新 UpdateTx(ctx context.Context, tx *gorm.DB, data *Gift) error FindByPlatformGift(ctx context.Context, platform string, giftId string) (*Gift, error) } customGiftModel struct { *defaultGiftModel } ) // NewGiftModel returns a model for the database table. func NewGiftModel(conn *gorm.DB) GiftModel { return &customGiftModel{ defaultGiftModel: newGiftModel(conn), } } func (m *customGiftModel) Transaction(ctx context.Context, tx *gorm.DB, fn func(tx *gorm.DB) error) error { return withTx(ctx, m.conn, tx).Transaction(func(tx *gorm.DB) error { return fn(tx) }) } func (m *customGiftModel) InsertTx(ctx context.Context, tx *gorm.DB, data *Gift) error { err := withTx(ctx, m.conn, tx).Create(&data).Error return err } func (m *customGiftModel) UpdateTx(ctx context.Context, tx *gorm.DB, data *Gift) error { err := withTx(ctx, m.conn, tx).Save(data).Error return err } func (m *customGiftModel) FindByPlatformGift(ctx context.Context, platform string, giftId string) (*Gift, error) { var resp Gift db := m.conn.WithContext(ctx) err := db.Model(&Gift{}). Where("platform = ? AND gift_id = ?", platform, giftId). Take(&resp).Error switch err { case nil: return &resp, nil case gormc.ErrNotFound: return nil, ErrNotFound default: return nil, err } }