golang time.Now 提示0000-00-00 错误

正常用gorm定义数据库模型的时候, 时间用的是time.Time
但是很多时候是没有初始化这个时间的, 默认的时间是0000-00-00 这种的
插入数据库救护报错:

Incorrect datetime value: '0000-00-00' for column 'start_time'
这边请问下有啥好的解决办法呢

阅读 14.5k
4 个回答
    type Person struct {
        StartTime time.Time `json:"start_time" gorm:"column:start_time"`
    }

    func (p *Person) BeforeCreate(scope *gorm.Scope) error {
        scope.SetColumn("start_time", time.Now())
        return nil
    }

定义成指针就行 *time.Time,然后数据库字段允许为 null。这样在未赋值的情况下,插入的就是 null 了。

  1. 数据库允许null,程序插入null值
  2. 程序里面给start_time一个默认值
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题