GORM无法使用.Find()查询所有记录。

huangapple go评论66阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年8月12日 06:25:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73327462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定