登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-10 11:03:34 407浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《GORM 无法使用 .Find() 查询所有记录》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在尝试编写一个函数来查询与一组条件匹配的所有结果并将它们保存在结构体切片中。

// 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))
}

根据 gorm 文档(https://gorm.io/docs/query.html#retreering-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,但在返回后则无法打印。


正确答案


使用 DB.QueryAllRecords(db, outputObject, Conditions) 代替

理论要掌握,实操不能落!以上关于《GORM 无法使用 .Find() 查询所有记录》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>