GORM 1 升级 GORM 2 的修改点

文章目录

    在写公司内部的一个办公系统时,想趁机把 Gorm 版本升级一下。

    大部分靠 go build 的编译错误提示,修改完成。

    依赖修改

    github.com/jinzhu/gorm
    

    变更为

    gorm.io/gorm
    

    cannot use “mysql” (type string) as type gorm.Dialector in argument to gorm.Open

    -       DB, err = gorm.Open("mysql", dataSourceName)
    +      DB, err = gorm.Open(mysql.Open(dataSourceName), &gorm.Config{})
    

    LogMode undefined (type *gorm.DB has no field or method LogMode)

    之前用这个来做 debug 模式时,打印生成的 SQL。

    暂时没招到对应的 GORM 2 的设置方法。

    cannot use &count (type *int) as type *int64 Model.Count

    GORM 2 的 count 需要传入 int64 类型。

    Update want (string, interface {})

     not enough arguments in call to models.DB.Model(&models.User{}).Where("id = ?", uid.(int)).Update
            have (models.UserProfile)
            want (string, interface {})
    

    使用 Updates 替代 Update.

    参考:

    https://gorm.io/docs/update.html

    Create Omit

    db.Omit(“CreditCard”).Create(&user)

    如果不使用 Omit 会发现:

    INSERT INTO `user` (`nick_name`,`avatar`) VALUES ... ON DUPLICATE KEY UPDATE `id`=`id`
    

    参考

    https://gorm.io/zh_CN/docs/v2_release_note.html

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式