亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

time.Time 的子類型不使用 gorm lib 創建列

time.Time 的子類型不使用 gorm lib 創建列

Go
阿波羅的戰車 2023-08-07 14:41:21
我正在嘗試向數據庫添加時間戳,并返回帶有表示時間戳的數字的 json,而不是時間戳的當前字符串表示形式;本質上是壓倒一切的元帥time.Timetype JSONTime time.Timefunc (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
查看完整描述

2 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

我終于明白了。


有幾個問題:


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")

}


查看完整回答
反對 回復 2023-08-07
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

嘗試一下


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"`

}


查看完整回答
反對 回復 2023-08-07
  • 2 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號