I am trying to write a function to query all results that match a set of conditions and save them in a struct slice.
// Queries the database for the given set of fields and some string conditions specified as a map
func QueryAllRecords(db *gorm.DB, outputObject interface{}, conditions map[string]interface{}) {
result := db.Where(conditions).Find(&outputObject)
if result.Error != nil {
panic(result.Error)
}
log.Println(Utils.CreateLogMessage("Queried all records", outputObject))
}
According to the GORM docs (https://gorm.io/docs/query.html#Retrieving-all-objects), I can query all records using the .Find()
function and then specify the struct where the output of the query will be saved.
This is where I make my function call to QueryAllRecords
:
var outputObject []Models.Product
conditions := map[string]interface{}{"name": "Sample Product"}
DB.QueryAllRecords(db, outputObject, conditions)
fmt.Println(outputObject)
When I try to print outputObject
, I get an empty an empty slice []
. It seems like the .Find(&outputObject)
is not saving the result in the slice like I want it to. I can successfully print outputObject
within the function itself, but not after it has returned.
CodePudding user response:
Use the DB.QueryAllRecords(db, outputObject, conditions)
instead
CodePudding user response:
Pass the reference/pointer of the outputObject
array to QueryAllRecords
, or return it from the function.
I can successfully print outputObject within the function itself, but not after it has returned.