GORM如何获取查询对象的属性

package main

import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "time"
)

type User struct {
    ID int
    Name string
    CreatedTime time.Time
}


func main() {
    dsn := "root:123456@tcp(127.0.0.1:3306)/more?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil{
        return
    }
    //db.AutoMigrate(&User{})
    user := User{}
    fmt.Print(user)  //{0  0001-01-01 00:00:00 +0000 UTC}
    db.First(&user)
    fmt.Print(user) //{3 test2 0001-01-01 00:00:00 +0000 UTC}
}

你查询的东西都在结构体实例中,然后就可以用user.name这种了。

原文地址:https://www.cnblogs.com/qinghuaL/p/14847764.html