GORM
该笔记使用的gorm是对应的v2版本的gorm ,如果是使用的v1版本可能会有很大的区别,特此提醒;
快速开始
go get gorm.io/gorm
go get gorm.io/driver/mysql
package main
import (
"fmt"
huge "github.com/dablelv/go-huge-util"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
)
type Ziop struct {
gorm.Model
Name string
Age int
Like string
}
func (z *Ziop) TableName() string { return "grid_ziop" }
func main() {
dataSource := "ziop:ziop@/demo?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dataSource), &gorm.Config{})
if err != nil {
log.Fatal(err, "数据库连接失败")
}
err = db.AutoMigrate(&Ziop{})
if err != nil {
log.Fatal(err)
}
// 新增
ziop := Ziop{
Name: "ziop",
Age: 21,
Like: "codings",
}
db.Create(&ziop)
//查询
var z []Ziop
ziopDb := db.Model(&Ziop{})
ziopDb.Where("Age > ?", 23).Find(&z)
//修改
ziopDb.Where("id in (?)", []int{1, 2, 3}).Updates(Ziop{
Name: "Ziop",
}).First(&z)
// 软删除
ziopDb.Delete("id = ?", 1)
// 硬删除
ziopDb.Unscoped().Delete("id = ?", 1)
// 打印
json, err := huge.ToIndentJSON(&z)
fmt.Printf("Ziop = %+v", json)
}
V2特性
Update Hook 支持 Changed
当使用 Update
,Updates
更新时,您可以在 BeforeUpdate
, BeforeSave
Hook 中使用 Changed
方法来检查字段是否有更改.
func (user *User) BeforeUpdate(tx *gorm.DB) error {
if tx.Statement.Changed("Name", "Admin") { // if Name or Admin changed
tx.Statement.SetColumn("Age", 18)
}
if tx.Statement.Changed() { // 如果任何字段有变动
tx.Statement.SetColumn("Age", 18)
}
return nil
}
// update field `Name` to `Jinzhu`
db.Model(&user).Update("Name", "Jinzhu")
// update field `Name` to `Jinzhu`, `Admin` to false
db.Model(&user).Updates(map[string]interface{}{"name": "Jinzhu", "admin": false})
// Update none zero fields when using struct as argument, will only update `Name` to `Jinzhu`
db.Model(&user).Updates(User{Name: "Jinzhu", Admin: false})
// update selected fields `Name`, `Admin`,`Admin` will be updated to zero value (false)
db.Model(&user).Select("Name", "Admin").Updates(User{Name: "Jinzhu"})
// update selected fields exists in the map, will only update field `Name` to `Jinzhu`
db.Model(&user).Select("Name", "Admin").Updates(map[string]interface{}{"Name": "Jinzhu"})
// Attention: `Changed` will only check the field value of `Update` / `Updates` equals `Model`'s field value, it returns true if not equal and the field will be saved
// Changed("Name") => true
db.Model(&User{ID: 1, Name: "jinzhu"}).Updates(map[string]interface{"name": "jinzhu2"})
// Changed("Name") => false, `Name` not changed
db.Model(&User{ID: 1, Name: "jinzhu"}).Updates(map[string]interface{"name": "jinzhu"})
// Changed("Name") => false, `Name` not selected to update
db.Model(&User{ID: 1, Name: "jinzhu"}).Select("Admin").Updates(map[string]interface{"name": "jinzhu2", "admin": false})
// Changed("Name") => true
db.Model(&User{ID: 1, Name: "jinzhu"}).Updates(User{Name: "jinzhu2"})
// Changed("Name") => false, `Name` not changed
db.Model(&User{ID: 1, Name: "jinzhu"}).Updates(User{Name: "jinzhu"})
// Changed("Name") => false, `Name` not selected to update
db.Model(&User{ID: 1, Name: "jinzhu"}).Select("Admin").Updates(User{Name: "jinzhu2"})