Search code examples
gogo-gormgo-gin

Function which returns list of struct from gorm database returning nil?


I'm trying to make a function that will output all of the contents from a table as a slice of the struct the table is.

func FetchAll(parameter interface{}) []interface{} {
    var model interface{}

    var resultArray []interface{}

    db := common.GetDB()
    rows, err := db.Model(parameter).Where(parameter).Rows()
    if err != nil {
        fmt.Print(err.Error())
        return nil
    }
    for rows.Next() {
        db.ScanRows(rows, &model)
        resultArray = append(resultArray, model)
    }
    fmt.Println(resultArray)
    return resultArray
}

Usage:

c.JSON(200, FetchAll(&ProductImage{ProductID: productID}))

But the output is the following:

[<nil>,<nil>,<nil>]

Why is it?


Solution

  • the type of model can't be interface{}

    you can use var model = map[string]interface{}{}

    Easier to write:

    func FetchAll(parameter interface{}) []map[string]interface{} {
        var resultArray []map[string]interface{}
    
        db := common.GetDB()
        err := db.Model(parameter).Where(parameter).Find(&resultArray).Error
        if err != nil {
            fmt.Print(err)
            return nil
        }
        fmt.Println(resultArray)
        return resultArray
    }