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

如何返回用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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式