How can i get all rows in a gorm as reflect type slice

Viewed 38

I want to write a function that returns all rows in a table using a reflective type.

func (rt *tableRouter) select_table_DB(ctx context.Context, vars url.Values, tableType reflect.Type, name string) (reflect.Value, error) {
    db, err := db.Open(rt.dbcfg)
    if err != nil {
        return reflect.Value{}, err
    }
    defer db.Close()

    rows := reflect.MakeSlice(reflect.SliceOf(tableType), 0, 0)
    db.WithContext(ctx).Table(name).Find(&rows)

    return rows, err
}

This only returns {}

1 Answers

You must provide a concret object (which contains a set of exported fields) to receive data from database so than gorm knows how database table columns map to object members. And reflect.Value is not such an object, maybe you could try to use reflect.Value.Interface() which returns an interface whose underlying data is an concret object. By the way, gorm/gen is a nice tool to automatically generate CURD code for your model. (enter link description here)

Related