// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package model import ( "smart-auth/consts" "smart-auth/errors" "time" "github.com/jaryhe/gopkgs/logger" "github.com/jinzhu/gorm" jsoniter "github.com/json-iterator/go" "go.uber.org/zap" ) // 替换encoding/json包 var json = jsoniter.ConfigCompatibleWithStandardLibrary type TDevice struct { Id uint64 `gorm:"primary_key"` ProjectId int64 `gorm:"column:project_id"` ProviderId int64 `gorm:"column:provider_id"` Name string `gorm:"column:name"` Sn string `gorm:"column:sn"` Addr string `gorm:"column:addr"` DeviceCode int32 `gorm:"column:device_code"` Lon float32 `gorm:"column:lon"` Lat float32 `gorm:"column:lat"` XCoord float32 `gorm:"column:x_coord"` YCoord float32 `gorm:"column:y_coord"` Status int `gorm:"column:status"` VerifyStatus int `gorm:"column:verify_status"` Key string `gorm:"column:key"` CreatedAt string `gorm:"column:created_at"` UpdatedAt string `gorm:"column:updated_at"` } func (TDevice) TableName() string { return "t_device" } func (p *TDevice) Insert(db *gorm.DB) error { timeNow := time.Now().Format(consts.TimeSecondLayOut) p.CreatedAt = timeNow p.UpdatedAt = timeNow err := db.Create(p).Error if err != nil { fields, _ := json.MarshalToString(*p) logger.Error("mysql", zap.String("sql", "insert into t_device"), zap.String("fields", fields), zap.String("error", err.Error())) } return err } func (p *TDevice) Delete(db *gorm.DB, filter map[string]interface{}) error { err := db.Where(filter).Delete(p).Error if err != nil { fields, _ := json.MarshalToString(filter) logger.Error("mysql", zap.String("sql", "delete from t_device"), zap.String("fields", fields), zap.String("error", err.Error())) } return err } // 通过结构体变量更新字段值, gorm库会忽略零值字段。就是字段值等于0, nil, "", false这些值会被忽略掉,不会更新。如果想更新零值,可以使用map类型替代结构体。 func (p *TDevice) UpdateSome(db *gorm.DB, filed map[string]interface{}) error { if filed == nil { return errors.ParamsError } timeNow := time.Now().Format(consts.TimeSecondLayOut) filed["updated_at"] = timeNow 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 *TDevice) 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 *TDevice) QueryAll(db *gorm.DB, filter map[string]interface{}) (list []TDevice, 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 }