问题描述
在gorm快速入门中的这一行代码:
type Product struct {
gorm.Model
Code string
Price uint
}
// 迁移 schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "", Price: 100})
// Update
db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段
注释中写道进更新非零值字段,意味着如果Code的值如果为空就无法更新。
解决办法
在gorm中有sql.NullString类型如下:
type NullString struct {
String string
Valid bool // Valid is true if String is not NULL
}
类型中包含String类型和bool类型,string类型用于存储值,bool类型为true时表示值为空值
解决后的代码如下:
package main
import (
"database/sql"
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func main() {
dsn := "root:qweasdzxc321@tcp(127.0.0.1:3306)/grom_test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
if err != nil {
panic(err)
}
//定义一个表结构,将表结构智界生成对应的表
type Product struct {
gorm.Model
Code sql.NullString
Price uint
}
// 迁移 schema
db.AutoMigrate(&Product{}) //此处应该有sql语句
// 新增
db.Create(&Product{Code: sql.NullString{"D42", true}, Price: 100})
// Update - 更新多个字段
db.Model(&product).Updates(Product{Price: 200, Code: sql.NullString{"F42", true}}) // 仅更新非零值字段
Delete - 删除 product
//db.Delete(&product, 1)
}
通过gorm中sql.NullString类型我们可以解决零值更新问题!