douyongwan5946 2017-01-17 19:45
浏览 672

golang-> gorm:如何在mysql中将sql.NullInt64用作int(10)?

type Contact struct {
  gorm.Model
  PersonID sql.NullInt64
}

type Person struct {
  gorm.Model
}

I am trying to use gorm with mysql in the previuos code but I have the following problem:

I want:

  • Use sql.NullInt64 to work easily with null values.
  • Use the base model definition gorm.Model, including fields ID, CreatedAt, UpdatedAt, DeletedAt.
  • Add a constraint Db.Model(&models.Contact{}).AddForeignKey.

My problem:

  • Person.ID become "int(10)" in mysql.
  • Contact.PersonID become "bigint(20)"
  • MySql need the same type for pk and fk.

Some body can help me to solve this?

  • 写回答

1条回答 默认 最新

  • dosrmo0442 2017-03-20 22:21
    关注

    The "magic" on gorm.Model is only the name of the fields, any struct with these fields look like this according to the gorm documentation, at the end of Conventions

    For example: Save records having UpdatedAt field will set it to current time.

    Or

    Delete records having DeletedAt field, it won't be deleted from database, but only set field DeletedAt's value to current time, and the record is not findable when querying, refer Soft Delete

    So solve the issue is very easy, this is the code for my case:

    package models
    
    import "time"
    
    type Model struct {
        ID        uint `gorm:"primary_key;type:bigint(20) not null auto_increment"`
        CreatedAt time.Time
        UpdatedAt time.Time
        DeletedAt *time.Time `sql:"index"`
    }
    

    So, now I only need use it as base model :)

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向