猿问

time.Time 的子类型不使用 gorm lib 创建列

我正在尝试向数据库添加时间戳,并返回带有表示时间戳的数字的 json,而不是时间戳的当前字符串表示形式;本质上是压倒一切的元帅time.Time


type JSONTime time.Time


func (j *JSONTime) UnmarshalJSON(data []byte) error {

    if string(data) == "null" {

        return nil

    }

    millis, err := strconv.ParseInt(string(data), 10, 64)

    if err != nil {

        return err

    }

    *j = JSONTime(time.Unix(0, millis*int64(time.Millisecond)))

    return err

}


func (t JSONTime) MarshalJSON() ([]byte, error) {

    //do your serializing here

    stamp := fmt.Sprintf("%d", time.Time(t).Unix()*1000)

    return []byte(stamp), nil

}

type table struct {

    ID        int64    `gorm:"primary_key;auto_increment"json:"id"`

    CreatedAt JSONTime json:"createdAt"`

    UpdatedAt JSONTime json:"updatedAt"`

}

我遇到的问题是上面的代码只是忽略了数据库中列的创建(创建了其他字段)。我什至手动创建了该列,但 gorm 也不添加数据。


我相信编组和解组工作,但问题在于使用它们之前(即将列添加到数据库)


我在这里做错了什么?

我正在使用MySQL和库gorm


阿波罗的战车
浏览 103回答 2
2回答

斯蒂芬大帝

我终于明白了。有几个问题:1-MarshalJSONand UnmarshalJSON仅适用于数据库交互之前和之后2-结构table定义没有正确的gorm定义:type tablestruct {    ID        int64            `gorm:"primary_key;auto_increment"json:"id"`    CreatedAt timeLib.JSONTime `gorm:"type:timestamp;default:current_timestamp"json:"createdAt"`    UpdatedAt timeLib.JSONTime `gorm:"type:timestamp;default:current_timestamp ON update current_timestamp"json:"updatedAt"`}3-由于 typeJSONTime是一个新类型,驱动程序不知道如何转换它,所以我们需要重写Value:func (jsonTime JSONTime) Value() (driver.Value, error) {    return time.Time(jsonTime), nil}4-最后我们需要重写Scan以便将数据库值转换为JSONTime值func (jsonTime *JSONTime) Scan(value interface{}) error {    if value == nil {        *jsonTime = JSONTime(time.Now())        return nil    }    if readTime, err := driver.DefaultParameterConverter.ConvertValue(value); err == nil {        if convertedTime, ok := readTime.(time.Time); ok {            *jsonTime = JSONTime(convertedTime)            return nil        }    }    return errors.New("failed to scan TIME")}

慕斯王

尝试一下type JSONTime struct {    time.Time}type BaseModel struct {    ID        uint     `gorm:"autoIncrement;primary_key" json:"id"`    CreatedAt JSONTime `gorm:"type:timestamp;default:current_timestamp" json:"created_at"`    UpdatedAt JSONTime `gorm:"type:timestamp;default:current_timestamp" json:"updated_at"`    DeletedAt JSONTime `gorm:"type:timestamp;default:current_timestamp" json:"deleted_at"`}
随时随地看视频慕课网APP

相关分类

Go
我要回答