简体   繁体   中英

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

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 {}

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM