Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do UUID in Golangs Gorm?

I have the following model...

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
}

I've tried several different ways, but this way throws (pq: relation "users" does not exist). I have no related models, it's literally just that one model.

I've tried using...

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

Along with a uuid lib, but had no luck with that either.

like image 328
Ewan Valentine Avatar asked Apr 07 '16 20:04

Ewan Valentine


People also ask

What is UUID OSSP?

The uuid-ossp module provides functions to generate universally unique identifiers (UUIDs) using one of several standard algorithms. There are also functions to produce certain special UUID constants. This module is only necessary for special requirements beyond what is available in core PostgreSQL.

How does Gorm know which table?

It uses the name of your type. Here the type is User so gorm will use the users table by default.


1 Answers

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
}
like image 124
Ewan Valentine Avatar answered Oct 04 '22 22:10

Ewan Valentine