package model import ( "context" "git.noahlan.cn/northlan/ntools-go/gorm-zero/gormc" "github.com/jinzhu/now" "gorm.io/gorm" "time" ) var _ UserCheckInModel = (*customUserCheckInModel)(nil) type ( // UserCheckInModel is an interface to be customized, add more methods here, // and implement the added methods in customUserCheckInModel. UserCheckInModel interface { userCheckInModel InsertTx(ctx context.Context, tx *gorm.DB, data *UserCheckIn) error // FindThisWeek 查询用户本周签到记录 FindThisWeek(ctx context.Context, tx *gorm.DB, userId int64) ([]UserCheckIn, error) // CheckInToday 查询用户本日是否已签到 CheckInToday(ctx context.Context, tx *gorm.DB, userId int64) (bool, error) } customUserCheckInModel struct { *defaultUserCheckInModel } ) // NewUserCheckInModel returns a model for the database table. func NewUserCheckInModel(conn *gorm.DB) UserCheckInModel { return &customUserCheckInModel{ defaultUserCheckInModel: newUserCheckInModel(conn), } } func (m *customUserCheckInModel) InsertTx(ctx context.Context, tx *gorm.DB, data *UserCheckIn) error { err := withTx(ctx, m.conn, tx).Create(&data).Error return err } func (m *customUserCheckInModel) FindThisWeek(ctx context.Context, tx *gorm.DB, userId int64) ([]UserCheckIn, error) { db := withTx(ctx, m.conn, tx) // 取签到时间大于本周一的所有该用户签到记录,按签到时间升序排列 var resp []UserCheckIn err := db.Model(&UserCheckIn{}). Where("user_id = ? AND check_in_time >= ", userId, now.Monday()). Order("check_in_time ASC").Find(resp).Error switch err { case nil: return resp, nil case gormc.ErrNotFound: return []UserCheckIn{}, nil default: return nil, err } } func (m *customUserCheckInModel) CheckInToday(ctx context.Context, tx *gorm.DB, userId int64) (bool, error) { db := withTx(ctx, m.conn, tx) n := time.Now() var count int64 err := db.Table(m.table). Where("user_id = ? AND check_in_time >= ? AND check_in_time <= ?", userId, now.With(n).BeginningOfDay(), now.With(n).EndOfDay()). Count(&count). Error switch err { case nil: return count > 0, nil case gormc.ErrNotFound: return false, nil default: return false, err } }