简体   繁体   English

如何使用 Gorm 向现有列添加默认值

[英]How to add defaults to existing columns with Gorm

I'm using gorm and have a model like so:我正在使用 gorm 并有一个 model 像这样:

type MyModel struct {
    CreationTime      time.Time 
    UpdateTime        time.Time
}

I realized after deploying my DB that creation time and update time weren't adding times when items were being created and updated: I tried to fix this by updating the model to the following:在部署我的数据库后,我意识到创建时间和更新时间并没有增加创建和更新项目的时间:我尝试通过将 model 更新为以下内容来解决此问题:

type MyModel struct {
    CreationTime      time.Time       `gorm:"default:current_timestamp"`
    UpdateTime        time.Time       `gorm:"default:current_timestamp ON update current_timestamp"`
}

However, auto migrating like the following won't apply these defaults on the already existing tables!但是,像下面这样的自动迁移不会将这些默认值应用于已经存在的表!

 db.AutoMigrate(&MyModel{})

Is there any way I can use the built in migration functions to add defaults to columns?有什么方法可以使用内置的迁移功能将默认值添加到列? I searched the docs and it seems like I can only change the type of existing columns, If not?我搜索了文档,似乎我只能更改现有列的类型,如果不能? any recommendations for a why to simply add defaults to a column via migrations?关于为什么通过迁移简单地将默认值添加到列的任何建议?

Have you tried sql tag?你试过sql标签吗?

`sql:"DEFAULT:current_timestamp"`

The automigration provided by gorm doesn't delete or modify your columns and for good reasons, it's not safe. gorm 提供的自动迁移不会删除或修改您的列,并且有充分的理由,它是不安全的。 I had a similar issue.我有一个类似的问题。 I needed to drop the null constraint from one of my columns and couldn't find anything that does that in gorm, and I'm pretty sure it doesn't.我需要从我的一个专栏中删除 null 约束,但在 gorm 中找不到任何可以做到这一点的东西,我很确定它不会。 I wrote my own function for doing this.我为此编写了自己的 function。 You can easily do something similar.您可以轻松地做类似的事情。

Please take a look at these two commits: this and this .请看一下这两个提交: thisthis What you can basically do this is to define a method for the Dialect interface and then write an implementation for that method for the commonDialect type (and the postgres type, if required).你基本上可以做的是为Dialect接口定义一个方法,然后为commonDialect类型(和postgres类型,如果需要)编写该方法的实现。

Hope this helps.希望这可以帮助。 Feel free to ask me if you face any problems with implementation or have any doubts.如果您在实施方面遇到任何问题或有任何疑问,请随时问我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM