19

私は次のモデルを持っています...

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
}

いくつかの異なる方法を試しましたが、この方法では(pq: relation "users" does not exist). 関連するモデルはありません。文字通りその 1 つのモデルだけです。

使ってみた...

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

uuid ライブラリと一緒ですが、それも運がありませんでした。

4

6 に答える 6

13

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
}
于 2016-04-10T17:36:13.440 に答える
1

エラー(pq: relation "users" does not exist)は通常、テーブル usersがデータベースに存在しないことを意味します。2 つのモデル間の関係とは何の関係もありません。

したがって、基本的には、最初にデータベースにテーブルを作成する必要があります(または@Apinの提案に従ってデータベースを自動移行します)。そして、同じコードを再実行してみてください。

于 2016-04-08T01:51:28.580 に答える
0

None of these worked for me using gorm v1.21. Here was my solution. Note that I'm using the satori/go.uuid library for generating UUID, but code with google's library is near identical.

type UUIDBaseModel struct {
    ID        uuid.UUID       `gorm:"primary_key" json:"id"`
    CreatedAt time.Time  `json:"created_at"`
    UpdatedAt time.Time  `json:"updated_at"`
    DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}

func (base *UUIDBaseModel) BeforeCreate(tx *gorm.DB) error {
    uuid := uuid.NewV4().String()
    tx.Statement.SetColumn("ID", uuid)
    return nil
}
于 2021-10-12T06:34:53.800 に答える