Search code examples
gogo-gorm

How do I get column names and values from a gorm object?


I'd like to write a function that can take any object loaded from the database (via gorm) and print out all of the column names and values. Obviously, the key part is the ability to pass any of my gorm models into this function. I haven't shown these below, as they're all very simple.

What I have so far is a function that takes an interface, and some test code to invoke 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 run, this prints out the type, and then panics:

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

I'm relatively new to go, so welcome your thoughts. It seems my possible options are:

  • Use reflection (if that works on slices)
  • Look up the fields in the model somehow?
  • Other ideas?

Thank you.


Solution

  • try this approach :

    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 slice of struct.(avoid it instead call above function in loop if working with slice.)

    2-i am passing this struct to above func

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

    3- getting output :-

    Names [Name Id]
    values [Zargham 2]