【问题标题】:How to return the record that I create it with Create() of Gorm?如何返回我用 Gorm 的 Create() 创建的记录?
【发布时间】:2018-12-09 04:32:50
【问题描述】:

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

例如,我在下面的代码中用Create()创建了一个用户:

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

我想退回这条user记录,怎么办?

更新:

我需要使用Where() 吗?像这样:

db.Where("name = ?", "Jack").First(&user) 

【问题讨论】:

  • 只返回user 值。

标签: go go-gorm


【解决方案1】:

根据official docsDefault value section 创建后,您将更新对象内部的所有属性。所以使用你传递给Create的对象应该足够了

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

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2020-01-05
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多