Home  >  Article  >  Backend Development  >  How to get column names and values ​​from Gorm object?

How to get column names and values ​​from Gorm object?

WBOY
WBOYforward
2024-02-09 15:30:091231browse

如何从 Gorm 对象获取列名称和值?

php Editor Strawberry In programming development, we often use Gorm objects for database operations. Sometimes, we need to get the column name and corresponding value from the Gorm object. So, how to achieve this requirement? In Gorm, we can get the properties and values ​​of the object through reflection, and combine it with Gorm's labels to get the column names. Next, I will introduce in detail how to get column names and values ​​​​from Gorm objects. Let’s take a look!

Question content

I want to write a function that can take any object loaded from the database (via gorm) and print out all column names and values. Obviously the key part is the ability to pass any of my Gorm models into this function. I don't show these below because they are all simple.

What I have so far is a function with an interface, and some test code that calls it:

func testfunc(s interface{}) {

    // type
    v := reflect.TypeOf(s)

    fmt.Println(v)

    // fields?
    for i := 0; i < v.NumField(); i++ {
        fmt.Println(i)
    }
}
trans := make([]orm.Trans, 0)

    db.Where("state = ?", state.FINISHED).Limit(1).Find(&trans)

    testfunc(trans)

When running, the type will be printed, and then a panic will occur:

[]orm.Trans
panic: reflect: call of reflect.Value.NumField on slice Value

I'm a newbie, so your ideas are welcome. It seems that my possible choices are:

  • Use reflection (if applicable to slicing)
  • Find a field in a model somehow?
  • Any other ideas?

Thanks.

Solution

Try this method:

func testfunc(x interface{}){
        v := reflect.ValueOf(x)
        s := reflect.TypeOf(x)
        names:=make([]interface{},v.NumField())
        values := make([]interface{}, v.NumField())

        for i := 0; i < v.NumField(); i++ {
                values[i] = v.Field(i).Interface()
                names[i] = s.Field(i).Name
        }
        fmt.Println("Names",names)
        fmt.Println("values",values)

}

1 - You are passing a slice of struct. (If using slicing, avoid calling the above function in a loop.)

2-I am passing this structure to the function above

x := struct {
                Name string
                Id int
        }{"Zargham", 2}

3-Get the output:-

Names [Name Id]
values [Zargham 2]

The above is the detailed content of How to get column names and values ​​from Gorm object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete