英文:
GORM unable to query all records using .Find()
问题
我正在尝试编写一个函数,用于查询满足一组条件的所有结果,并将它们保存在一个结构体切片中。
根据GORM文档(https://gorm.io/docs/query.html#Retrieving-all-objects),我可以使用.Find()
函数查询所有记录,然后指定查询结果将保存在的结构体。
这是我对QueryAllRecords
进行函数调用的地方:
var outputObject []Models.Product
conditions := map[string]interface{}{"name": "Sample Product"}
DB.QueryAllRecords(db, outputObject, conditions)
fmt.Println(outputObject)
当我尝试打印outputObject
时,我得到一个空的切片[]
。似乎.Find(&outputObject)
没有像我希望的那样将结果保存在切片中。我可以在函数内成功打印outputObject
,但在函数返回后就无法打印了。
英文:
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.
答案1
得分: 0
请使用DB.QueryAllRecords(db, outputObject, conditions)
代替。
英文:
Use the DB.QueryAllRecords(db, outputObject, conditions)
instead
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论