1. gorm operation mysql:
1.1 installation gorm
Gorm official website: https://gorm.io/zh_CN/docs/connecting_to_the_database.html
GitHub address of Gorm: https://github.com/go-gorm/gorm
go get -u gorm.io/gorm
1.2 install mysql driver
go get -u gorm.io/driver/mysql
two Connect to Mysql, automatically migrate and generate data tables, and perform basic addition, deletion, modification and query
package main import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) type UserInfo struct { ID uint Name string Gender string Hobby string } func main() { // Connect to mysql database dsn := "name:password@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(err) } // Create table automatic migration (corresponding structure to data table) db.AutoMigrate(&UserInfo{}) // Create data row //U1: = userinfo {1, "seven meters", "male", "Basketball"} //db.Create(&u1) // Save the first data in the query table to u var u UserInfo db.First(&u) fmt.Println(u) // to update db.Model(&u).Update("Hobby", "Two color ball") fmt.Println(u) // delete db.Delete(&u) }
three Common label options for structure definition models
// Define model type User struct { gorm.Model // Embed four fields: ID, CreatedAt, UpdatedAt and DeletedAt Name string Age sql.NullInt64 // Zero value type Birthday *time.Time Email string `gorm:"type:varchar(100);unique_index"` // unique_index: unique index Role string `gorm:"size:255"` // Set the field size to 255 MemberNumber *string `gorm:"unique;not null"` // Set the member number to be unique and not empty Num int `gorm:"AUTO_INCREMENT"` // Set num to auto increment type Address string `gorm:"index:addr"` // Create an index named addr for the address field IgnoreMe int `gorm:"-"` // Ignore this field }
Structure tags
Tags are optional when you declare a model using a structure. gorm supports the following tags:
Supported Struct tags
Structure Tag | describe |
---|---|
Column | Specify column name |
Type | Specify column data type |
Size | Specifies the column size. The default value is 255 |
PRIMARY_KEY | Specify the column as the primary key |
UNIQUE | Specify columns as unique |
DEFAULT | Specify column defaults |
PRECISION | Specify column precision |
NOT NULL | Specify the column as non NULL |
AUTO_INCREMENT | Specifies whether the column is self incrementing |
INDEX | Create an index with or without a name, and create a composite index if multiple indexes have the same name |
UNIQUE_INDEX | and INDEX Similar, except that a unique index is created |
EMBEDDED | Set structure to embedded |
EMBEDDED_PREFIX | Sets the prefix of the embedded structure |
- | Ignore this field |
Associated tags
Structure Tag | describe |
---|---|
MANY2MANY | Specify connection table |
FOREIGNKEY | Set foreign keys |
ASSOCIATION_FOREIGNKEY | Set associated foreign keys |
POLYMORPHIC | Specify polymorphic type |
POLYMORPHIC_VALUE | Specify polymorphic values |
JOINTABLE_FOREIGNKEY | Specifies the foreign key of the join table |
ASSOCIATION_JOINTABLE_FOREIGNKEY | Specifies the associated foreign key for the join table |
SAVE_ASSOCIATIONS | Whether to automatically complete the operation related to save |
ASSOCIATION_AUTOUPDATE | Automatically complete update related operations |
ASSOCIATION_AUTOCREATE | Do you want to automatically complete the operations related to create |
ASSOCIATION_SAVE_REFERENCE | Automatically complete the operations related to the referenced save |
PRELOAD | Whether to automatically complete preloading related operations |
4. Agreement on primary key, table name and column name
Primary Key
GORM uses the field named ID as the primary key of the table by default.
type User struct { ID string // The field named 'ID' will be the primary key of the table by default Name string } // Use 'AnimalID' as the primary key type Animal struct { AnimalID int64 `gorm:"primary_key"` Name string Age int64 }
Table Name
By default, the table name is the plural of the structure name, for example:
type User struct {} // The default table name is ` users` // Set User's table name to ` profiles` func (User) TableName() string { return "profiles" }
Some operations based on table name
// Find a var u1 User db.Table("user").First(&u1) fmt.Println(u1) // Find multiple var u []User db.Table("user").Find(&u) fmt.Println(u) // Find by criteria var u2 []User db.Table("user").Where("name = ?", "Zhang San").Find(&u2) fmt.Println(u2) // Find by criteria and delete db.Table("user").Where("role = ?", "front02").Delete(1)
Column Name
Column names are generated by underlining field names
type User struct { ID uint // column name is `id` Name string // column name is `name` Birthday time.Time // column name is `birthday` CreatedAt time.Time // column name is `created_at` }
You can use the struct tag to specify the column name:
type Animal struct { AnimalId int64 `gorm:"column:beast_id"` // set column name to `beast_id` Birthday time.Time `gorm:"column:day_of_the_beast"` // set column name to `day_of_the_beast` Age int64 `gorm:"column:age_of_the_beast"` // set column name to `age_of_the_beast` }
five Timestamp tracking
CreatedAt
If the model has CreatedAt field whose value will be the time when the record was first created.
db.Create(&user) // `CreatedAt ` will be the current time // You can use the 'Update' method to change the value of 'CreateAt' db.Model(&user).Update("CreatedAt", time.Now())
UpdatedAt
If the model has an UpdatedAt field, the value of this field will be the time of each record update.
db.Save(&user) // `UpdatedAt ` will be the current time db.Model(&user).Update("name", "jinzhu") // `UpdatedAt ` will be the current time
DeletedAt
If the model has a DeletedAt field, when calling Delete to Delete the record, the DeletedAt field will be set to the current time instead of directly deleting the record from the database.
Reference link: https://liwenzhou.com/posts/Go/gorm/