猿问

你如何在 Golangs Gorm 中做 UUID?

我有以下型号...


type User struct {

    ID        string  `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`

    FirstName string `form:"first_name" json:"first_name,omitempty"`

    LastName  string `form:"last_name" json:"last_name,omitempty"`

    Password  string `form:"password" json:"password" bindind:"required"`

    Email     string `gorm:"type:varchar(110);unique_index" form:"email" json:"email,omitempty" binding:"required"`

    Location  string `form:"location" json:"location,omitempty"`

    Avatar    string `form:"avatar" json:"avatar,omitempty"`

    BgImg     string `form:"bg_img" json:"bg_img,omitempty"`

    CreatedAt time.Time

    UpdatedAt time.Time

    DeletedAt time.Time

}

我尝试了几种不同的方法,但是这种方法会抛出(pq: relation "users" does not exist). 我没有相关的模型,它实际上只是一个模型。


我试过用...


func (user *User) BeforeCreate(scope *gorm.Scope) error {

    scope.SetColumn("ID", uuid.NewV4())

    return nil

}

与 uuid lib 一起,但也没有运气。


喵喔喔
浏览 1273回答 3
3回答

HUWWW

原来我试图将 UUID 存储为错误的类型,我在做...func (user *User) BeforeCreate(scope *gorm.Scope) error {    scope.SetColumn("ID", uuid.NewV4())    return nil}当它需要...func (user *User) BeforeCreate(scope *gorm.Scope) error {    scope.SetColumn("ID", uuid.NewV4().String())    return nil}

慕莱坞森

为此,您将需要gorm和go.uuidgo get github.com/jinzhu/gormgo get github.com/satori/go.uuid尝试创建您自己的模型基础模型,而不是gorm.Model像这样:type Base struct { ID         string     `sql:"type:uuid;primary_key;default:uuid_generate_v4()"` CreatedAt  time.Time  `json:"created_at"` UpdatedAt  time.Time  `json:"updated_at"` DeletedAt  *time.Time `sql:"index" json:"deleted_at"`}然后,您将使用在创建任何记录之前调用的方法填充此字段,如下所示:func (base *Base) BeforeCreate(scope *gorm.Scope) error { id, err := uuid.NewV4() if err != nil {   return err } return scope.SetColumn("ID", uuid.String())}因此,对于您的特定情况,您将拥有:type User struct {    Base    FirstName string `form:"first_name" json:"first_name,omitempty"`    LastName  string `form:"last_name" json:"last_name,omitempty"`    Password  string `form:"password" json:"password" bindind:"required"`    Email     string `gorm:"type:varchar(110);unique_index" form:"email" json:"email,omitempty" binding:"required"`    Location  string `form:"location" json:"location,omitempty"`    Avatar    string `form:"avatar" json:"avatar,omitempty"`    BgImg     string `form:"bg_img" json:"bg_img,omitempty"`}可以在此处找到有关此的更多详细信息

长风秋雁

对于postgresql,这是我所做的:go get github.com/google/uuid使用uuid.UUID(来自“github.com/google/uuid”)作为类型,例如ID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"`为 postgres 数据库添加 uuid-ossp 扩展,例如如果不存在则创建扩展“uuid-ossp”;然后,当您调用 DB 的 Create() 方法时,会自动生成 uuid。
随时随地看视频慕课网APP

相关分类

Go
我要回答