doufen1890 2018-12-08 16:32
浏览 1628
已采纳

如何返回用Gorm的Create()创建的记录?

How to return the record that I create it with Create() of Gorm?

For example,I create a user with Create() in the code below:

package main

import (
    "apiserver/model"
    "fmt"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)


func main() {
    db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=postgres dbname=exampledb password=123 sslmode=disable")
    if err != nil {
        fmt.Println(err)
    }
    defer db.Close()   

    db.AutoMigrate(&model.User{})
    user := User{Name: "Jack", Age: 18}
    db.Create(&user)
}

I want to return this user record,how to do it?

update:

Do I need to do it with Where()? Like this:

db.Where("name = ?", "Jack").First(&user) 
  • 写回答

1条回答 默认 最新

  • drgawfsf1069 2018-12-08 19:19
    关注

    According to official docs and Default value section after creation, you get all properties updated inside the object. So it should be enough to use the object which reference you passed to Create

    user := User{Name: "Jack", Age: 18}
    db.Create(&user)
    fmt.Println(user.Name, user.Age)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?