postgresql - 你如何在 Golang Gorm 中使用 UUID?

标签 postgresql go go-gorm

我有以下模型...

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 库,但也没有运气。

最佳答案

原来我试图将 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
}

关于postgresql - 你如何在 Golang Gorm 中使用 UUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36486511/

相关文章:

go - 'type DoNotCompare [0]func()' 如何阻止 Golang 中的可比性

string - 如何将多个字符串和int合并成一个字符串

json - 反序列化嵌套的 JSON,或者简单地在 Go 中传递它

go - 数据库查询命令正在生成奇怪的 sql 查询

postgresql - 改变 pg_config

python - 结果后端的 Celery celery_taskmeta 表在任务完成之前不保存

go - 将 fizzbuzz 上的输出与 switch case 语句混淆

GORM 'NOT IN' 子查询

sql - 设置字符串的最后一个字母等于 PostgreSQL

angularjs - 不区分大小写的环回过滤器