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)
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)