Files
learn-golang/go-gorm-demo/crud_update.go
2025-12-26 17:56:02 +08:00

57 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
//type User struct {
// ID uint `gorm:"primaryKey"`
// Name string `gorm:"size:100"`
// Email string `gorm:"size:100;unique"`
// Age int
// UpdatedAt time.Time
//}
func main() {
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
db.AutoMigrate(&User{})
// 插入测试数据
user := User{Name: "Alice", Email: "alice@example.com", Age: 30}
db.Create(&user)
// 1. 更新单个字段
db.Model(&User{}).Where("id = ?", user.ID).Update("name", "Alice Updated")
fmt.Println("Updated single field")
// 2. 更新多个字段(使用 map
db.Model(&User{}).Where("id = ?", user.ID).Updates(map[string]interface{}{
"name": "Alice Smith",
"age": 31,
})
fmt.Println("Updated multiple fields (map)")
// 3. 更新多个字段(使用 struct仅更新非零值
db.Model(&User{}).Where("id = ?", user.ID).Updates(User{
Name: "Alice Johnson",
Age: 32,
})
fmt.Println("Updated multiple fields (struct)")
// 4. 强制更新零值字段
db.Model(&User{}).Where("id = ?", user.ID).Update("age", 0)
fmt.Println("Updated age to zero")
// 5. 批量更新
db.Model(&User{}).Where("age > ?", 25).Update("age", gorm.Expr("age + ?", 1))
fmt.Println("Batch update completed")
// 查询最终结果
var finalUser User
db.First(&finalUser, user.ID)
fmt.Printf("Final user: %s (age=%d)\n", finalUser.Name, finalUser.Age)
}