How do you do UUID in Golangs Gorm?

后端 未结 3 2138
闹比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 15:43

    The error (pq: relation "users" does not exist) usually means that, the table users does not exists in the database. It has nothing to do with the relationship between two models.

    So basically, You first need to create the table in the database (Or auto migrate the database As per @Apin suggest). And try to re-run the same code.

    0 讨论(0)
  • 2021-02-19 16:01

    Turns out I was trying to store the UUID as the wrong type, I was doing...

    func (user *User) BeforeCreate(scope *gorm.Scope) error {
        scope.SetColumn("ID", uuid.NewV4())
        return nil
    }
    

    When it needed to be...

    func (user *User) BeforeCreate(scope *gorm.Scope) error {
        scope.SetColumn("ID", uuid.NewV4().String())
        return nil
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题