gorm中動態使用表名


用戶表(前台、后台)

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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM