duanjiao7440 2017-04-26 11:37
浏览 46
已采纳

Gorm-通过迁移升级列约束

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条回答 默认 最新

  • duanpan3166 2017-05-09 23:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题