Gorm quick start
Gorm is the ORM framework of Go language, which is characterized by:
- Full feature ORM (almost all features)
- Model Association (one to one, one to many, one to many (reverse), many to many, polymorphic Association)
- Hook (Before/After Create/Save/Update/Delete/Find)
- Preload
- affair
- Composite primary key
- SQL constructor
- auto migrate
- journal
- Writing extensible plug-ins based on GORM callback
- Full characteristic test coverage
- Developer friendly
Quick start:
-
install
go get -u github.com/jinzhu/gorm
-
Connect to database:
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") if err!= nil{ panic(err) } defer db.Close()
-
Add, delete, modify and check
The basic information is as follows:
// UserInfo user information type UserInfo struct { ID uint Name string Gender string HA string }
Add:
u1 := UserInfo{3, "Withered vine", "male", "Basketball"} db.Create(&u1)
Query:
var u = new(UserInfo) db.First(u) fmt.Printf("%#v\n", u)
Modification:
db.Model(&u).Update("hobby", "Two color ball")
Delete:
db.Delete(&u)
All codes:
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) // UserInfo user information type UserInfo struct { ID uint Name string Gender string HA string } func main() { db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") if err!= nil{ panic(err) } defer db.Close() u1 := UserInfo{3, "Withered vine", "male", "Basketball"} u2 := UserInfo{4, "topgoer.com", "female", "Football"} // Create record db.Create(&u1) db.Create(&u2) // query var u = new(UserInfo) db.First(u) fmt.Printf("%#v\n", u) var uu UserInfo db.Find(&uu, "hobby=?", "Football") fmt.Printf("%#v\n", uu) // to update db.Model(&u).Update("hobby", "Two color ball") delete db.Delete(&u) }
Model definition:
The model is generally the structure of Golang and the basic data type or pointer of Go.
example:
type User struct { gorm.Model Name string Age sql.NullInt64 Birthday *time.Time Email string `gorm:"type:varchar(100);unique_index"` Role string `gorm:"size:255"` //Set the size of the field to 255 bytes MemberNumber *string `gorm:"unique;not null"` // Set the memberNumber field to be unique and not empty Num int `gorm:"AUTO_INCREMENT"` // Set Num field self increment Address string `gorm:"index:addr"` // Create an index named 'addr' for Address IgnoreMe int `gorm:"-"` //Ignore this field }
Supported structure labels:
label | explain |
---|---|
Column | Specifies the name of the column |
Type | Specifies the type of column |
Size | Specifies the size of the column. The default is 255 |
PRIMARY_KEY | Specify a column as the primary key |
UNIQUE | Specify a unique column |
DEFAULT | Specifies the default value for a column |
PRECISION | Specifies the precision of the column's data |
NOT NULL | The data of the specified column is not empty |
AUTO_INCREMENT | Specifies whether the data of a column is self incremented |
INDEX | Create an index with or without a name, and create a composite index with the same name |
UNIQUE_INDEX | Similar to index, create a unique index |
EMBEDDED | Set struct to embedded |
EMBEDDED_PREFIX | Sets the prefix name of the embedded structure |
- | Ignore these fields |
standard:
gorm.Model is a structure containing some basic fields, including ID, CreatedAt, UpdatedAt and DeletedAt.
You can use it to embed into the model, or you can use it to build your own model.
// gorm.Model definition type Model struct { ID uint `gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time } // Inject the fields' ID ',' createdat ',' updatedat 'and' deletedat 'into the' User 'model type User struct { gorm.Model Name string } // Declare Gorm Model model type User struct { ID int Name string }
gorm uses ID as the primary key name by default:
type User struct { ID string // The field name 'ID' will be used as the default primary key name } // Set the field 'AnimalID' as the default primary key type Animal struct { AnimalID int64 `gorm:"primary_key"` Name string Age int64 }
Specify table name:
// Create 'Delete' with 'User' structure_ Users ` table db.Table("deleted_users").CreateTable(&User{}) var deleted_users []User db.Table("deleted_users").Find(&deleted_users) SELECT * FROM deleted_users; db.Table("deleted_users").Where("name = ?", "jinzhu").Delete() DELETE FROM deleted_users WHERE name = 'jinzhu';
Modify table name:
You can use any rule for table names by defining the DefaultTableNameHandler field.
gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string { return "prefix_" + defaultTableName; }
Timestamp tracking:
For models with a CreatedAt field, it will be set to the current time when the record was first created.
For the model with UpdatedAt field, it will be set to the current time when the record is updated.
db.Create(&user) // Set 'CreatedAt' to the current time // You can use the 'Update' method to change the default time db.Model(&user).Update("CreatedAt", time.Now()) db.Save(&user) // Set 'UpdatedAt' to the current time db.Model(&user).Update("name", "jinzhu") // Set 'UpdatedAt' to the current time
Automatic migration:
Judge whether the UserInfo information is changed. If it is changed, it will be migrated automatically, that is, a new column will be generated. If there is no such table, it will be created.
db.AutoMigrate(&UserInfo{})