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 關注
- 1222 瀏覽
添加回答
舉報
