Home > Article > Backend Development > How to get column names and values from Gorm object?
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!
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:
Thanks.
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!