Field Filtering
When creating or updating data using struct data, especially during updates, some fields may not need updating. Therefore, corresponding fields should not be assigned values. For example:
type Book struct {
Id uint
Name string
Author string
Price float64
PubTime *gtime.Time `orm:"publish_time"`
}
data := Book{
Name: "Linux驱动开发入门与实践",
PubTime: gtime.New("2023-10-11"),
}
_, err = dao.Book.Ctx(ctx).Where("id", 13).Data(data).Update()
Updating like this would update id
, author
, and price
to their respective zero values: 0, "", 0.
To solve this issue, there are several solutions:
Specify Fields to Update Using Fields
dao.Book.Ctx(ctx).Fields("name", "publish_time").Where("id", 13).Data(data).Update()
Exclude Fields Not to Update Using FieldsEx
dao.Book.Ctx(ctx).FieldsEx("id,author,price").Where("id", 13).Data(data).Update()
Filter Empty Values Using OmitEmpty
data := Book{
Name: "Linux驱动开发入门与实践",
Price: 0,
PubTime: nil,
}
dao.Book.Ctx(ctx).Where("id", 13).OmitEmpty().Data(data).Update()
With this method, values like 0 and nil
will be ignored and not updated.
Using do
Object for Field Filtering
When using gf gen dao
, each table generates a corresponding do
object. Using the do
object as a parameter automatically filters empty values.
data := do.Book{
Name: "Linux驱动开发入门与实践",
Price: 0,
PublishTime: nil,
}
dao.Book.Ctx(ctx).Where("id", 13).Data(data).Update()
Using this approach, non-nil
zero values can also be updated.
The do
object can also be used to pass query conditions, automatically filtering empty values:
where := do.Book{
Author: "郑强",
Id: 13,
PublishTime: nil,
}
books, err := dao.Book.Ctx(ctx).Where(where).All()
// Equivalent to
books, err := dao.Book.Ctx(ctx).Where("id", 13).Where("author", "郑强").All()