How do you do UUID in Golangs Gorm?

后端 未结 3 2157
闹比i
闹比i 2021-02-19 15:24

I have the following model...

type User struct {
    ID        string  `sql:\"type:uuid;primary_key;default:uuid_generate_v4()\"`
    FirstName string `form:\"f         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 16:08

    For this you will need gorm and go.uuid

    go get github.com/jinzhu/gorm
    
    go get github.com/satori/go.uuid
    

    Try creating your own model base model in place of gorm.Model like so:

    type Base struct {
     ID         string     `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
     CreatedAt  time.Time  `json:"created_at"`
     UpdatedAt  time.Time  `json:"update_at"`
     DeletedAt *time.Time `sql:"index" json:"deleted_at"`
    }
    

    You would then populate this field using a method called before creation of any record, like so:

    func (base *Base) BeforeCreate(scope *gorm.Scope) error {
     uuid, err := uuid.NewV4()
     if err != nil {
      return err
     }
     return scope.SetColumn("ID", uuid.String())
    }
    

    Therefore, for your particular case, you would have:

    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"`
    }
    

    More details on this can be found here

提交回复
热议问题