如何正确使用Gorm自动增量?

问题描述 投票:0回答:2

我有一个 Go 结构体,它定义了一个由

gorm
管理的表。它包括一个自动递增的唯一整数主键。

type CreatedSurvey struct {
    ...
    Id int `json:"id" gorm:"primaryKey;autoIncrement:true;unique"`
    ...
}

每个

CreatedSurvey
对象都有自己独特的
Id
,并且它是从模板创建的,该模板具有自己独特的模板
Id
(
SurveyTemplateId
) 字段,可用于将创建的对象追溯到其模板。当前端应用程序调用触发创建新
CreatedSurvey
的 API 端点时,它会提供模板中的所有信息,包括此模板
SurveyTemplateId
。最初,这个
SurveytemplateId
被编组到
CreatedSurvey
Id
字段。对于 0 的
Id
,调用
MyDb.DB.Create(&survey)
时不会造成任何问题,
autoIncrement
可以正常运行。但是,如果提供的
Id
字段为
> 0
,则
autoIncrement
不会发生,并且由于属性的主键性质,冲突可能会导致错误。

为了避免此问题,在编组

Id
后,我将
0
的值显式设置为
JSON

    var createdSurvey surveys.CreatedSurvey
    err := ctx.ShouldBindJSON(&createdSurvey)
    if err != nil {
        restErr := errors.NewBadRequestError("invalid json body")
        ctx.JSON(restErr.Status, restErr)
        return
    }
    createdSurvey.Id = 0

这可以避免创建时出现任何问题。

result := users_db.DB.Create(&survey)

这个可以,但是看起来不干净,似乎不符合

Go
的一般清洁度。

我应该以不同的方式使用

gorm
吗?或者这是最好的选择?

database rest go auto-increment go-gorm
2个回答
0
投票

试试这个:

type CreatedSurvey struct {
...
Id uint64 `json:"id" sql:"AUTO_INCREMENT" gorm:"primary_key"`
...
}

0
投票

类型用户结构{ gorm.模型 Id uint

json:"id" gorm:"unique;primaryKey;autoIncrement"
名称字符串
json:"name"
用户名字符串
json:"username" gorm:"unique"
电子邮件字符串
json:"email" gorm:"unique"
密码字符串
json:"password"
创建时间.时间
json:"createdAt" 
}

© www.soinside.com 2019 - 2024. All rights reserved.