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.

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题