add zero time.Time filtering for omitempty feature of gdb.Model

This commit is contained in:
John
2020-03-30 20:44:36 +08:00
parent 7e0fa8e0cd
commit c10f73f1f7
2 changed files with 47 additions and 4 deletions

View File

@ -8,9 +8,11 @@ package gdb
import (
"fmt"
"github.com/gogf/gf/container/gmap"
"github.com/gogf/gf/container/gset"
"github.com/gogf/gf/internal/empty"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/text/gstr"
"time"
)
// getModel creates and returns a cloned model of current model if <safe> is true, or else it returns
@ -45,9 +47,25 @@ func (m *Model) doFilterDataMapForInsertOrUpdate(data Map, allowOmitEmpty bool)
}
// Remove key-value pairs of which the value is empty.
if allowOmitEmpty && m.option&OPTION_OMITEMPTY > 0 {
m := gmap.NewStrAnyMapFrom(data)
m.FilterEmpty()
data = m.Map()
tempMap := make(Map, len(data))
for k, v := range data {
if empty.IsEmpty(v) {
continue
}
// Special type filtering.
switch r := v.(type) {
case time.Time:
if r.IsZero() {
continue
}
case gtime.Time:
if r.IsZero() {
continue
}
}
tempMap[k] = v
}
data = tempMap
}
if len(m.fields) > 0 && m.fields != "*" {

View File

@ -13,6 +13,7 @@ import (
"github.com/gogf/gf/container/gmap"
"github.com/gogf/gf/util/gutil"
"testing"
"time"
"github.com/gogf/gf/database/gdb"
@ -2098,3 +2099,27 @@ func Test_Model_FieldsExStruct(t *testing.T) {
t.Assert(n, 10)
})
}
func Test_Model_OmitEmpty_Time(t *testing.T) {
table := createInitTable()
defer dropTable(table)
gtest.C(t, func(t *gtest.T) {
type User struct {
Id int `orm:"id" json:"id"`
Passport string `orm:"password" json:"pass_port"`
Password string `orm:"password" json:"password"`
Time time.Time `orm:"create_time" `
}
user := &User{
Id: 1,
Passport: "111",
Password: "222",
Time: time.Time{},
}
r, err := db.Table(table).OmitEmpty().Data(user).WherePri(1).Update()
t.Assert(err, nil)
n, err := r.RowsAffected()
t.Assert(err, nil)
t.Assert(n, 1)
})
}