I am trying to fetch all data from a table. It returns all data but it is displaying only the last record. I am using GORM and GIN with Golang.
I tried to create a struct and pass that struct to the Find
method.
type MpCountry struct{
id uint
Iso string
Name string
Nicename string
Iso3 string
Numcode uint
phonecode uint
}
Code:
countries:= DbModel.MpCountry{}
DbModel.DB.Debug().Find(&countries)
fmt.Println(countries)
fmt.Println("test")
log.Printf("%+v", countries)
return &countries
Output
SELECT * FROM `mp_countries`
[239 rows affected or returned ]
{id:0 Iso:ZW Name:ZIMBABWE Nicename:Zimbabwe Iso3:ZWE Numcode:716 phonecode:0}
You are only passing in a struct, not a slice of structs. It is therefore replacing the values in the struct, until it reaches the last record.
Instead, pass in a pointer to a slice:
countries := &[]DbModel.MpCountry{}
DbModel.DB.Debug().Find(countries)