3 回答
TA贡献1874条经验 获得超12个赞
原来我试图将 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
}
TA贡献1810条经验 获得超4个赞
为此,您将需要gorm和go.uuid
go get github.com/jinzhu/gorm
go 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"`
}
可以在此处找到有关此的更多详细信息
TA贡献1757条经验 获得超7个赞
对于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。
- 3 回答
- 0 关注
- 1272 浏览
添加回答
举报
