package model import ( "fmt" "time" "github.com/shopspring/decimal" "github.com/sirupsen/logrus" "github.com/spf13/viper" "gogs.daxia.dev/huanan/pkg.daxia.dev/db" ) type RoomType int const ( RoomTypeFree RoomType = 0 //免费房 RoomTypeNormal RoomType = 1 //普通房 ) type Room struct { ID uint `gorm:"primarykey"` CreatedAt time.Time UpdatedAt time.Time Name string `gorm:"varchar(40); comment:房间名称"` Password string `gorm:"varchar(40); comment:房间密码"` BaseAmount decimal.Decimal `gorm:"varchar(40); comment:底分"` RoomType RoomType `gorm:"varchar(40); comment:房间类型"` Chair1 uint32 `gorm:"int; comment:ID,0表示空"` Chair2 uint32 `gorm:"int; comment:ID,0表示空"` Chair3 uint32 `gorm:"int; comment:ID,0表示空"` Chair4 uint32 `gorm:"int; comment:ID,0表示空"` Chair5 uint32 `gorm:"int; comment:ID,0表示空"` } func (Room) TableName() string { return viper.GetString("table_prefix") + "room" } func (p Room) Init() error { if db.GetDB().Migrator().HasTable(p) { return nil } if err := db.GetDB().Migrator().CreateTable(p); err != nil { return err } //初始化数据 for i := 0; i < 10; i++ { err := db.GetDB().Create(&Room{ ID: 0, Name: fmt.Sprintf("房%d", i+1), Password: "", BaseAmount: decimal.NewFromInt(3), RoomType: RoomTypeFree, }).Error if err != nil { logrus.Fatal(err) } } return nil } func (p *Room) GetByID(roomID uint32) error { err := db.GetDB().Model(p).First(p).Error if err != nil { logrus.Error(err) return err } return nil } func (p *Room) GetByUserID(userID uint32) error { err := db.GetDB().Model(p).Where("chair1 = ? or chair2 = ? or chair3 = ? or chair4 = ? or chair5 = ?", userID, userID, userID, userID, userID).First(p).Error if err != nil { logrus.Error(err) return err } return nil } func (p Room) GetAll() ([]Room, error) { roomModelList := make([]Room, 0) err := db.GetDB().Model(p).Scan(&roomModelList).Error if err != nil { logrus.Error(err) return nil, err } return roomModelList, nil } func (p *Room) GetRoomUserList(roomID uint32) ([]uint32, error) { err := db.GetDB().Model(p).First(p).Error if err != nil { logrus.Error(err) return nil, err } return []uint32{p.Chair1, p.Chair2, p.Chair3, p.Chair4, p.Chair5}, nil }