package models import ( "gorm.io/gorm" "time" ) type Device struct { Id string `gorm:"column:id;primary_key;" json:"id"` Name string `gorm:"column:name" json:"name"` Addr string `gorm:"column:addr" json:"addr"` Floor string `gorm:"column:pos" json:"pos"` Ext string `gorm:"column:ext" json:"ext"` Ip string `gorm:"column:ip" json:"ip"` CreateTime int64 `gorm:"column:create_time;autoCreateTime;" json:"-"` UpdateTime int64 `gorm:"column:update_time;autoUpdateTime" json:"-"` DeleteTime int64 `gorm:"column:delete_time" json:"-"` } func (d *Device) TableName() string { return "devices" } func (d *Device) FindById(id string) error { return db.Table(d.TableName()).First(&d, "id = ?", id).Error } func (d *Device) FindAll() ([]Device, error) { var devices []Device if err := db.Table(d.TableName()).Find(&devices).Error; err != nil { return nil, err } return devices, nil } func (d *Device) Upsert() error { var existingDevice Device if err := db.Table(d.TableName()).Where("id = ?", d.Id).First(&existingDevice).Error; err != nil { if err == gorm.ErrRecordNotFound { // 记录不存在,创建新记录 db.Create(&d) } else { // 其他错误,你可以进行适当的处理 return err } } else { // 记录存在,更新现有记录 if d.Floor == "" || d.Ip == "" { return nil } existingDevice.Floor = d.Floor existingDevice.Ip = d.Ip db.Save(&existingDevice) } // 记录位置的历史, 给人脸抓拍匹配楼层 if existingDevice.Floor != "" { var pos = Positions{ DeviceId: d.Id, Pos: d.Floor, CreateTime: time.Now().Unix(), TimeString: time.Now().Format("2006-01-02 15:04:05"), } db.Create(&pos) } return nil }