Gorm – 使用迁移升级列约束

huangapple go评论83阅读模式
英文:

Gorm - upgrading columns constraint with migration

问题

如何使用gorm进行迁移?例如,我需要向列添加约束。我更改了我的模型(下面是一个简化的示例),但是根据文档,AutoMigrate方法不会更改列的约束。

那么如何实现呢?我在文档中找不到有用的信息。

起始模型:

type User struct {
    gorm.Model
    Name     string
}

我想要将其更新为:

type User struct {
    gorm.Model
    Name     string   `gorm:"not null"`
}
英文:

How do you perform a Migration with gorm? For example, I need to add a constraint to a column. I changed my model (simplified example below), but the AutoMigrate method, according to the docs, will not change column's constraints.

How do you achieve it then? I cannot find anything useful in the docs

Starting model:

type User struct {
    gorm.Model
    Name     string
}

I would like to update it like this:

type User struct {
    gorm.Model
    Name     string   `gorm:"not null"`
}

答案1

得分: 2

当添加一个not null约束时,如果现有记录不符合新的条件,则还需要添加一个default值。定义可以是这样的:

type User struct {
    gorm.Model
    Name     string   `gorm:"not null;default:'fillertext'"`
}

正如@putu所说,ALTER TABLE肯定可以工作,但是您仍然需要最初添加一个默认值,以确保不符合要求的行满足新的要求。一旦完成了这个步骤,如果您希望,可以删除默认值,然后迁移将按预期工作。

英文:

When adding a not null constraint, then a default value will also need to be added for when the existing records do not meet the new criteria. The definition could be something like:

type User struct {
    gorm.Model
    Name     string   `gorm:"not null;default:'fillertext'"`
}

As @putu said, ALTER TABLE will certainly work, but you would still need to add a default value initially to ensure the non-comforming rows meet the new requirements. Once this has been done you can remove the default value if you desire and the migration will work as intended from that point on.

huangapple
  • 本文由 发表于 2017年4月26日 19:37:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/43633108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定