dqol6556 2017-07-11 12:57
浏览 129

使用MySQL的表单插入既是主键又是默认值的字段

I want to have a table whose primary key is an auto-generated timestamp (I know it's generally not the best idea, but in my case it's OK) and it has another string field. This is the data structure that I use:

type GlobalDefault struct {
    Timestamp       time.Time           `gorm:"primary_key" sql:"DEFAULT:current_timestamp"`
    Version         string              `sql:"not null"`
}

When I use this data structure with AutoMigrate I indeed get a table with the timestamp as primary key, and I can even run insert into global_defaults (version) VALUES ('1.5.3'); and a new row would get inserted with an auto-generated timestamp.

My problem is that I can't insert records into this table using gorm. I use the following function:

func (repository *AgentRepository)SetGlobalDefault(version string) error {
    gd := GlobalDefault{ Version:version }
    return repository.connection.Create(&gd).Error
}

And when I call it I get the following error:

Received unexpected error could not convert argument of field Timestamp from int64 to time.Time

If I provide the timestamp explicitly, it works. I'm guessing that it has a problem with the default time ('0001-01-01 00:00:00 +0000 UTC') which is created when I don't specify it exactly.

Is there a way around this?

  • 写回答

1条回答 默认 最新

  • doutu9810 2017-07-13 18:34
    关注

    After comment interaction, drafting this answer.

    I'm guessing that it has a problem with the default time ('0001-01-01 00:00:00 +0000 UTC') which is created when I don't specify it exactly.

    The reason is, in Go data type has zero value, spec and good read here.

    For you, possible way is to use appropriate gorm callbacks to set or modify struct fields on before or after database interactions.

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能