When using the GORM ORM library in Golang, you may occasionally need to retrieve the database table name associated with a model. GORM provides multiple approaches for this purpose. Below, I will introduce two primary methods for obtaining table names from GORM models.
1. Using the TableName Method of the Model
In GORM, each model can specify its corresponding database table name by implementing the TableName method. If this method is not implemented, GORM defaults to using the snake-cased plural form of the struct name as the table name. For example:
gotype User struct { gorm.Model Name string } // Default table name is `users` // Custom table name func (User) TableName() string { return "my_custom_users" }
In this example, although the default table name is users, defining the TableName method allows you to specify the table name as my_custom_users. This method can be directly invoked to retrieve the table name:
gofunc main() { user := User{} tableName := user.TableName() // Returns "my_custom_users" fmt.Println(tableName) }
2. Using the ToTableName Method of the gorm Library
If you need to retrieve the table name without instantiating a model instance, or if you want to obtain the default table name without calling the model's TableName method, you can use the ToTableName method. This method belongs to the schema utility of the gorm library and directly parses the table name from the model's type information.
goimport ( "fmt" "gorm.io/gorm" "gorm.io/gorm/schema" ) type Product struct { gorm.Model Code string Price uint } func main() { // Initialize GORM db, _ := gorm.Open(...) // Assume database is properly configured // Use schema.Parse to obtain model schema information schema, _ := schema.Parse(&Product{}, &sync.Map{}, schema.NamingStrategy{}) // Retrieve table name tableName := schema.Table fmt.Println(tableName) // Default outputs "products" }
This approach is particularly suitable for retrieving table names when no database instance is available, or when writing generic functions that require table name operations.
Summary
Select the appropriate method based on your specific scenario. If you already have a model instance, using the TableName method is straightforward and efficient. If you need to retrieve the table name globally or without a model instance, the ToTableName method from gorm/schema is an excellent choice.