亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 gorm 從數據庫返回新創建的記錄

如何使用 gorm 從數據庫返回新創建的記錄

Go
不負相思意 2022-12-26 16:23:34
我有一個創建新用戶的函數,但是獲取用戶值的推薦方法不包括數據庫創建的自動生成的值(id,created_at)type User struct {    Id         string `json:"id" gorm:"primaryKey"`    Email      string `json:"email"`    Password   string `json:"password"`    Created_At string `json:"created_at"`    Updated_At string `json:"updated_at"`    Deleted_At string `json:"deleted_at"`}type UserRequest struct {    Email    string `json:"email"`    Password string `json:"password"`}func CreateUserRepo(newUser UserRequest) (*User, error) {    user := User{Email: newUser.Email, Password: newUser.Password}    fmt.Println(user)    result := services.PostgresSQLDB.Select("Email", "Password").Create(&user)    fmt.Println(result.RowsAffected)    if result.Error != nil {        modules.Logger.Error(result.Error)        return nil, result.Error    }    return &user, nil}你可以看到我為 id 和 created_at 得到了一個空字符串,盡管這些值是由我的數據庫自動生成的。{    "id": "",    "email": "[email protected]",    "password": "password",    "created_at": "",    "updated_at": "",    "deleted_at": ""}
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

我終于在不包含的情況下找到了答案。


添加默認的 return 子句,返回所有新創建的值。 https://gorm.io/docs/update.html#Returning-Data-From-Modified-Rows


Clauses.(clause.Returning{})

模型.go


type User struct {

    ID        uuid.UUID      `json:"id" gorm:"primaryKey:type:uuid"`

    Email     string         `json:"email"`

    Password  string         `json:"password"`

    CreatedAt time.Time      `json:"created_at"`

    UpdatedAt time.Time      `json:"updated_at"`

    DeletedAt gorm.DeletedAt `json:"deleted_at"`

}

存儲庫.go


func CreateUserRepo(newUser UserRequest) (*User, error) {


    hash, errHash := modules.HashPassword(newUser.Password)


    if errHash != nil {

        return nil, errHash

    }


    user := User{Email: newUser.Email, Password: *hash}

    result := services.PostgresSQLDB.Clauses(clause.Returning{}).Select("Email", "Password").Create(&user)

    fmt.Println(result.RowsAffected)

    fmt.Println(&user)


    if result.Error != nil {

        modules.Logger.Error(result.Error)

        return nil, result.Error

    }


    return &user, nil


}


查看完整回答
反對 回復 2022-12-26
?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

據我所知,GORM 不支持任何其他的主鍵整數自動遞增。BeforeCreate因此,要么將其保留在 PostgreSQL 端(就像您所做的那樣),要么在創建對象(使用鉤子)之前在 Go 中生成自己的 UUID 。


另外,gorm.Model定義如下:


type Model struct {

  ID        uint           `gorm:"primaryKey"`

  CreatedAt time.Time

  UpdatedAt time.Time

  DeletedAt gorm.DeletedAt `gorm:"index"`

}

您不必使用它,但如果不需要,請添加gorm:"primaryKey"到您的主鍵字段。默認情況下主字段有自動遞增,對于你的情況,我建議用禁用它autoIncrement:false。


type User struct {

    Id        uuid.UUID      `gorm:"primaryKey;autoIncrement:false" json:"id"`

    Email     string         `json:"email"`

    Password  string         `json:"password"`

}

當您讓 PostgreSQL 處理默認值(而不是 GORM)時,您必須再次查詢該對象才能訪問您的idUUID 和created_atTIMESTAMP。


另請注意,您可以GormValuerInterface在創建時使用 SQL Expr。但是您仍然需要再次查詢您的記錄。( https://gorm.io/docs/data_types.html#GormValuerInterface )


如果您有興趣在 Go 端處理所有問題,這里有一個帶和不帶gorm.Model.


package main


import (

    "fmt"

    "time"


    "github.com/google/uuid"

    "gorm.io/driver/sqlite"

    "gorm.io/gorm"

)


var DB *gorm.DB


type User struct {

    UUID      uuid.UUID `gorm:"primaryKey;autoIncrement:false"`

    Name      string

    CreatedAt time.Time

}


type UserWithGormModel struct {

    gorm.Model

    UUID uuid.UUID `gorm:"primaryKey;autoIncrement:false"`

    Name string

}


func (u *User) BeforeCreate(tx *gorm.DB) (err error) {


    // This is an example, refer to https://pkg.go.dev/github.com/google/UUID for good usage

    u.UUID = uuid.New()


    u.CreatedAt = time.Now()


    return

}


func (u *UserWithGormModel) BeforeCreate(tx *gorm.DB) (err error) {


    // This is an example, refer to https://pkg.go.dev/github.com/google/UUID for good usage

    u.UUID = uuid.New()


    return

}


func ConnectDatabase() {


    database, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})

    if err != nil {

        panic("failed to connect database")

    }


    if err != nil {

        panic("Failed to connect to database!")

    }


    database.AutoMigrate(&User{}, &UserWithGormModel{})


    DB = database

}


func main() {

    ConnectDatabase()


    user := User{Name: "Bob"}

    DB.Create(&user)

    fmt.Printf("User{UUID: %s, User.Name: %s, CreatedAt: %s}\n", user.UUID, user.Name, user.CreatedAt)


    user2 := UserWithGormModel{Name: "John"}

    DB.Create(&user2)

    fmt.Printf("UserWithGormModel{UUID: %s, Name: %s, CreatedAt: %s}\n", user2.UUID, user2.Name, user2.CreatedAt)

}

輸出:


User{UUID: 8551636a-540f-4733-8179-3f0cc45daf4f, User.Name: Bob, CreatedAt: 2022-06-28 11:40:10.9225724 +0200 CEST}

UserWithGormModel{UUID: 2a6f94bd-a42b-4316-90be-0e93ea5091a6, Name: John, CreatedAt: 2022-06-28 11:40:10.9318004 +0200 CEST}



查看完整回答
反對 回復 2022-12-26
  • 2 回答
  • 0 關注
  • 390 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號