乐闻世界logo
搜索文章和话题

How can I set COLLATION of a field to utf8_general_ci with GORM?

1个答案

1

When using GORM to interact with the database, if you need to set the collation of a specific field (e.g., to utf8_general_ci), you can achieve this by leveraging GORM's model definition capabilities.

In GORM, you can set the collation of a specific field by specifying collate in the field tag of the model. For instance, consider a User model with a Name field that you want to use the utf8_general_ci collation. You can define your model as follows:

go
type User struct { gorm.Model Name string `gorm:"collate:utf8_general_ci"` }

When GORM executes a migration operation, it sets the field attributes of the database table based on the model definition. Here is an example of how to use GORM for migration:

go
package main import ( "gorm.io/driver/mysql" "gorm.io/gorm" ) type User struct { gorm.Model Name string `gorm:"collate:utf8_general_ci"` } func main() { // Connect to database dsn := "username:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Auto migration mode db.AutoMigrate(&User{}) }

In this code snippet, we first define a User struct where the Name field specifies the use of the utf8_general_ci collation via the gorm:"collate:utf8_general_ci" tag. Then, in the main function, we connect to the database and call the AutoMigrate method, which creates or updates the database table based on the model definition.

By doing this, you can ensure that the Name field in the database has the collation set to utf8_general_ci, which is very useful for certain specific character sorting requirements.

2024年8月12日 18:16 回复

你的答案