安裝
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
gorm.Model模型
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
- gorm約定默認(rèn)將
ID
作為主鍵 - 我們可以將Model模型嵌入結(jié)構(gòu)體中
type user struct {
gorm.Model
Name string
}
字段標(biāo)簽
- 聲明 model 時(shí),tag 是可選的,GORM 支持以下 tag: tag 名大小寫不敏感忌卤,但建議使用 camelCase 風(fēng)格
type user struct {
ID uint `gorm:"primaryKey"`
Name string
}
連接到mysql數(shù)據(jù)庫
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
// 參考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 獲取詳情
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}
遷移
AutoMigrate()用于自動(dòng)遷移您的 schema,保持您的 schema 是最新的惨好。
db.AutoMigrate(&User{})
db.Migrator().CurrentDatabase() //返回當(dāng)前使用的數(shù)據(jù)庫名
其他遷移
- GORM 的 AutoMigrate 適用于大多數(shù)的遷移,如果您需要更加個(gè)性化的遷移工具 随闺,GORM 提供的一個(gè)通用數(shù)據(jù)庫接口可能對(duì)您有幫助。
// returns `*sql.DB`
db.DB()
創(chuàng)建記錄
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type user struct {
ID uint `gorm:"primaryKey"`
Name string
Age uint
}
func main() {
dsn := "user:pass@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 {
fmt.Println("err", err)
}
db.AutoMigrate(&user{})
u := user{
Name: "mac",
Age: 18,
}
result := db.Create(&u)
fmt.Println(u.ID) //返回ID
fmt.Println(result.Error) //返回error
fmt.Println(result.RowsAffected) //返回插入記錄的條數(shù)
}
用指定字段插入
db.Select("Name").Create(&u) //只插入Name字段
db.Omit("Name", ).Create(&u) //插入除Name以外的其他字段
批量插入
var users = []User{{Name: "person1"}, {Name: "person2"}, {Name: "person3"}}
db.Create(&users)
使用map插入
db.Model(&User{}).Create(map[string]interface{}{
"Name": "person", "Age": 18,
})
// batch insert from `[]map[string]interface{}{}`
db.Model(&User{}).Create([]map[string]interface{}{
{"Name": "person1", "Age": 18},
{"Name": "person2", "Age": 20},
})
查詢
// 獲取第一條記錄(主鍵升序)
db.First(&user)
// SELECT * FROM users ORDER BY id LIMIT 1;
// 獲取一條記錄蔓腐,沒有指定排序字段
db.Take(&user)
// SELECT * FROM users LIMIT 1;
// 獲取最后一條記錄(主鍵降序)
db.Last(&user)
// SELECT * FROM users ORDER BY id DESC LIMIT 1;
//獲取所有記錄
db.Find(&user)
//SELECT * FROM users
用主鍵檢索
db.First(&user, 10)
// SELECT * FROM users WHERE id = 10;
db.First(&user, "10")
// SELECT * FROM users WHERE id = 10;
db.Find(&users, []int{1,2,3})
// SELECT * FROM users WHERE id IN (1,2,3);
更新
保存所有字段
db.First(&user)
user.Name = "person"
user.Age = 18
db.Save(&user)
保存非零字段
db.Where("id=?",1).Update("name","jerry")
刪除
db.Delete(&user)
db.Where("name=?", "jerry").Delete(&user{})
根據(jù)主鍵刪除
db.Delete(&User{}, 10)
// DELETE FROM users WHERE id = 10;
db.Delete(&User{}, "10")
// DELETE FROM users WHERE id = 10;
db.Delete(&users, []int{1,2,3})
// DELETE FROM users WHERE id IN (1,2,3);
執(zhí)行原生SQL
raw()+scan()
type Result struct {
ID int
Name string
Age int
}
var result Result
db.Raw("SELECT id, name, age FROM users WHERE name = ?", 3).Scan(&result)
db.Raw("SELECT id, name, age FROM users WHERE name = ?", 3).Scan(&result)
var age int
db.Raw("SELECT SUM(age) FROM users WHERE role = ?", "admin").Scan(&age)
var users []User
db.Raw("UPDATE users SET name = ? WHERE age = ? RETURNING id, name", "person", 20).Scan(&users)
Exec() 原生SQL
db.Exec("DROP TABLE users")
db.Exec("UPDATE orders SET shipped_at = ? WHERE id IN ?", time.Now(), []int64{1, 2, 3})
// Exec with SQL Expression
db.Exec("UPDATE users SET money = ? WHERE name = ?", gorm.Expr("money * ? + ?", 10000, 1), "person")