用户表(前台、后台)
type User struct {
ID int `gorm:"primaryKey;autoIncrement"`
Name sql.NullString `gorm:"default:'隔壁老王'"`
Age uint8 `gorm:"default:55"`
UUID uuid.UUID
CreatedAt time.Time `gorm:"autoCreateTime"`
Deleted gorm.DeletedAt `gorm:"autoDeleteTime"`
}
type AdminUser struct {
ID int `gorm:"primaryKey;autoIncrement"`
Name sql.NullString `gorm:"default:'隔壁老王'"`
Age uint8 `gorm:"default:55"`
UUID uuid.UUID
CreatedAt time.Time `gorm:"autoCreateTime"`
Deleted gorm.DeletedAt `gorm:"autoDeleteTime"`
}
type DynamicUser interface {
IsAdmin() bool
}
func (*User) IsAdmin() bool {
return true
}
func (*AdminUser) IsAdmin() bool {
return false
}
动态获取表名
func UserTable(u DynamicUser) func(tx *gorm.DB) *gorm.DB {
return func(tx *gorm.DB) *gorm.DB {
if u.IsAdmin() {
return tx.Table("users")
}
return tx.Table("admin_users")
}
}
测试
type APIUser struct {
ID int
Name string
Age int
}
// TableName 不支持动态变化,它会被缓存下来以便后续使用。想要使用动态表名,你可以使用 Scopes,例如:
var apiUser APIUser
var user DynamicUser
user = &User{}
db.Scopes(UserTable(user)).Scan(&apiUser)
fmt.Println(apiUser)
user = &AdminUser{}
db.Scopes(UserTable(user)).Scan(&apiUser)
fmt.Println(apiUser)