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

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"`
}
- 2 回答
- 0 關注
- 126 瀏覽
添加回答
舉報