When using GORM, if your database table name is prefixed (for example:prefix_tcm_operation_logs
), you can customize itTableName
Method to handle table prefix.TableName
The method is where GORM uses to get the database table name, where you can dynamically add prefixes.
1. Method 1: Customize the table name through TableName
If you want all tables to have the same prefix, you can manually implement the TableName method in each model and dynamically splice the prefixes.
1.1 Implement TableName method
Assume that the database table prefix isprefix_
, you can define it in the modelTableName
Method to return the table name with a prefix.
package models import ( "fmt" "time" "/jinzhu/gorm" ) type TcmOperationLogs struct { ID uint64 `gorm:"primaryKey;autoIncrement;column:id" json:"id"` Action string `gorm:"type:varchar(255);column:action" json:"action"` Type string `gorm:"type:varchar(255);default:'';column:type" json:"type"` UserID string `gorm:"type:varchar(255);column:user_id" json:"user_id"` DoctorID string `gorm:"type:varchar(255);column:doctor_id" json:"doctor_id"` AdminID string `gorm:"type:varchar(255);column:admin_id" json:"admin_id"` Description string `gorm:"type:text;column:description" json:"description"` CreatedAt `gorm:"type:datetime;column:created_at" json:"created_at"` UpdatedAt `gorm:"type:datetime;column:updated_at" json:"updated_at"` } // TableName method returns the prefixed table namefunc (TcmOperationLogs) TableName() string { // Assume that the prefix is 'prefix_' return "prefix_tcm_operation_logs" }
In this way, every time GORM uses the TcmOperationLogs model, prefix_tcm_operation_logs will be automatically used as the table name.
2. Method 2: Global prefix configuration
If you want all tables in GORM to use the same prefix, you can automatically prefix all models through global configuration.
2.1 NamingStrategy configuration using GORM
In GORM v2, you can set the globalNamingStrategy
to prefix all table names.NamingStrategy
Allows you to customize GORM's table name generation rules.
package main import ( "fmt" "log" "/driver/mysql" "/gorm" "/gorm/schema" ) // Define the modeltype TcmOperationLogs struct { ID uint64 `gorm:"primaryKey;autoIncrement;column:id" json:"id"` Action string `gorm:"type:varchar(255);column:action" json:"action"` Type string `gorm:"type:varchar(255);default:'';column:type" json:"type"` UserID string `gorm:"type:varchar(255);column:user_id" json:"user_id"` DoctorID string `gorm:"type:varchar(255);column:doctor_id" json:"doctor_id"` AdminID string `gorm:"type:varchar(255);column:admin_id" json:"admin_id"` Description string `gorm:"type:text;column:description" json:"description"` CreatedAt `gorm:"type:datetime;column:created_at" json:"created_at"` UpdatedAt `gorm:"type:datetime;column:updated_at" json:"updated_at"` } func main() { // Connect to MySQL database dsn := "root:password@tcp(127.0.0.1:3306)/your_db?charset=utf8mb4&parseTime=True&loc=Local" db, err := ((dsn), &{ NamingStrategy: { TablePrefix: "prefix_", // Prefix all tables }, }) if err != nil { ("failed to connect to database: %v", err) } // Automatic migration err = (&TcmOperationLogs{}) if err != nil { ("failed to migrate database: %v", err) } // After that, all the table names of the models will be automatically prefixed ("Database connected and migrations completed") }
3. Method 3: Use custom DB and Model functions
Another way is to dynamically add prefixes by customizing database operation functions. This method is not common, but may be used in some special scenarios.
package main import ( "fmt" "log" "/driver/mysql" "/gorm" ) // Define the modeltype TcmOperationLogs struct { ID uint64 `gorm:"primaryKey;autoIncrement;column:id" json:"id"` Action string `gorm:"type:varchar(255);column:action" json:"action"` Type string `gorm:"type:varchar(255);default:'';column:type" json:"type"` UserID string `gorm:"type:varchar(255);column:user_id" json:"user_id"` DoctorID string `gorm:"type:varchar(255);column:doctor_id" json:"doctor_id"` AdminID string `gorm:"type:varchar(255);column:admin_id" json:"admin_id"` Description string `gorm:"type:text;column:description" json:"description"` CreatedAt `gorm:"type:datetime;column:created_at" json:"created_at"` UpdatedAt `gorm:"type:datetime;column:updated_at" json:"updated_at"` } func main() { // Connect to MySQL database dsn := "root:password@tcp(127.0.0.1:3306)/your_db?charset=utf8mb4&parseTime=True&loc=Local" db, err := ((dsn), &{}) if err != nil { ("failed to connect to database: %v", err) } // Custom query var logs []TcmOperationLogs ("prefix_tcm_operation_logs").Find(&logs) (logs) }
4. Summary
-
Method 1: Manually implemented in each model
TableName
Method to dynamically add prefixes. This is suitable for scenarios where each table has a different prefix. -
Method 2: Using GORM v2
NamingStrategy
Configuration, prefix all table names globally. This is suitable for all tables in the database to use the same prefix. -
Method 3:use
("prefix_tcm_operation_logs")
To manually specify the prefix. This method requires specifying the table name every time during query.
Usually, if all tables require the same prefix, useMethod 2CooperateNamingStrategy
It will be more concise and unified.
This is the end of this article about the implementation of the prefix of the Gin database table name in Golang. For more related content of the prefix of the Gin table name, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!