英文:
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
}
我正在尝试在上述代码中使用gorm与mysql,但是我遇到了以下问题:
我想要:
- 使用
sql.NullInt64
来轻松处理空值。 - 使用基本模型定义
gorm.Model
,包括字段ID
,CreatedAt
,UpdatedAt
,DeletedAt
。 - 添加约束
Db.Model(&models.Contact{}).AddForeignKey
。
我的问题是:
Person.ID
在mysql中变为"int(10)"
。Contact.PersonID
在mysql中变为"bigint(20)"
。- MySql需要pk和fk具有相同的类型。
有人可以帮助我解决这个问题吗?
<details>
<summary>英文:</summary>
type Contact struct {
gorm.Model
PersonID sql.NullInt64
}
type Person struct {
gorm.Model
}
I am trying to use [gorm][1] 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][2].
Some body can help me to solve this?
[1]: http://jinzhu.me/gorm/
[2]: https://stackoverflow.com/questions/16969060/mysql-error-1215-cannot-add-foreign-key-constraint/16969176#16969176
</details>
# 答案1
**得分**: 1
“gorm.Model”上的“magic”只是字段的名称,根据gorm文档,具有这些字段的任何“struct”都是这样的,参考[Conventions][1]。
例如:保存具有“UpdatedAt”字段的记录将将其设置为当前时间。
或者
删除具有“DeletedAt”字段的记录,它不会从数据库中删除,而只是将字段“DeletedAt”的值设置为当前时间,并且在查询时无法找到该记录,参考[Soft Delete][2]。
因此,解决这个问题非常简单,这是我这种情况的代码:
```go
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"`
}
所以,现在我只需要将其用作基本模型
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论