// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package model import ( "smart-auth/errors" "time" "github.com/jaryhe/gopkgs/logger" "github.com/jinzhu/gorm" "go.uber.org/zap" json2 "encoding/json" ) // 替换encoding/json包 type JsonStruct struct { } func (p *JsonStruct)MarshalToString(v interface{}) (string, error) { bytes, err := json2.Marshal(v) return string(bytes), err } func (p *JsonStruct)Marshal(v interface{}) ([]byte, error) { bytes, err := json2.Marshal(v) return bytes, err } func (p *JsonStruct)Unmarshal(bytes []byte, v interface{}) (error) { err := json2.Unmarshal(bytes, v) return err } var json = &JsonStruct{} type DeviceAll struct { ID int64 `gorm:"column:ID" json:"id"` SN string `gorm:"column:SN" json:"sn"` DeviceState int64 `gorm:"column:DeviceState" json:"devicestate"` Longitude string `gorm:"column:Longitude" json:"longitude"` Latitude string `gorm:"column:Latitude" json:"latitude"` DeviceCode uint32 `gorm:"column:DeviceCode"` Key string `gorm:"column:Key"` DeviceName string `gorm:"column:DeviceName"` SubId int64 `gorm:"column:SubId"` ProjectId int64 `gorm:"column:ProjectId"` ProviderId int64 `gorm:"column:ProviderId"` CreatedAt time.Time `gorm:"column:CreatedAt"` VerifyTime time.Time `gorm:"column:VerifyTime"` VerifyStatus int `gorm:"column:VerifyStatus"` ChannelId int64 `gorm:"column:ChannelId"` } func (DeviceAll) TableName() string { return "DeviceAll" } // 通过结构体变量更新字段值, gorm库会忽略零值字段。就是字段值等于0, nil, "", false这些值会被忽略掉,不会更新。如果想更新零值,可以使用map类型替代结构体。 func (p *DeviceAll) UpdateSome(db *gorm.DB, filed map[string]interface{}) error { if filed == nil { return errors.ParamsError } err := db.Model(p).Updates(filed).Error if err != nil { fields, _ := json.MarshalToString(filed) logger.Error("mysql", zap.String("sql", "update t_device"), zap.String("fields", fields), zap.String("error", err.Error())) } return err } func (p *DeviceAll) Update(db *gorm.DB, where map[string]interface{}, values map[string]interface{}) error { cond, val, err := whereBuild(where) if err != nil { return err } return db.Table(p.TableName()).Where(cond, val...).Updates(values).Error } func (p *DeviceAll) Query(db *gorm.DB, filter map[string]interface{}) error { err := db.Where(filter).Find(p).Error if err != nil { fields, _ := json.MarshalToString(filter) logger.Error("mysql", zap.String("sql", "select from t_device"), zap.String("fields", fields), zap.String("error", err.Error())) } return err } func (p *DeviceAll) QueryAll(db *gorm.DB, filter map[string]interface{}) (list []DeviceAll, err error) { err = db.Where(filter).Find(&list).Error if err != nil { fields, _ := json.MarshalToString(filter) logger.Error("mysql", zap.String("sql", "select from t_device"), zap.String("fields", fields), zap.String("error", err.Error())) } return list, err }