简体   繁体   English

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

[英]golang -> gorm: How I can use sql.NullInt64 to be int(10) in mysql?

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: 我试图在上一个代码中将gorm与mysql一起使用,但存在以下问题:

I want: 我想要:

  • Use sql.NullInt64 to work easily with null values. 使用sql.NullInt64可以轻松使用null值。
  • Use the base model definition gorm.Model , including fields ID , CreatedAt , UpdatedAt , DeletedAt . 使用基本模型定义gorm.Model ,包括字段IDCreatedAtUpdatedAtDeletedAt
  • Add a constraint Db.Model(&models.Contact{}).AddForeignKey . 添加约束Db.Model(&models.Contact{}).AddForeignKey

My problem: 我的问题:

  • Person.ID become "int(10)" in mysql. 在MySQL中, Person.ID变为"int(10)"
  • Contact.PersonID become "bigint(20)" Contact.PersonID变为"bigint(20)"
  • MySql need the same type for pk and fk . MySql的pk和fk需要相同的类型。

Some body can help me to solve this? 可以帮助我解决这个问题吗?

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 gorm.Model上的“魔术”仅是字段的名称,根据gorm文档, 约定结尾处的包含这些字段的任何struct都应如下所示

For example: Save records having UpdatedAt field will set it to current time. 例如:保存具有UpdatedAt字段的记录会将其设置为当前时间。

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 删除具有DeletedAt字段的记录,不会从数据库中删除它,而仅将字段DeletedAt的值设置为当前时间,并且在查询时找不到该记录,请参阅软删除

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 :) 因此,现在我只需要将其用作基本模型即可:)

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

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