使用GORM .Find()无法查询并返回全部记录问题求助
GORM查询结果无法同步到函数外部切片
我编写了QueryAllRecords函数,旨在通过GORM的.Find()方法查询符合条件的记录并保存到结构体切片中。根据GORM官方文档,该方法可将查询结果存入指定结构体,但调用函数后外部的切片仍为空,仅函数内部能正常打印查询结果。
函数代码
// 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)) }
调用代码
var outputObject []Models.Product conditions := map[string]interface{}{"name": "Sample Product"} DB.QueryAllRecords(db, outputObject, conditions) fmt.Println(outputObject)
问题原因
问题核心是Go的参数传递机制:你传递给函数的是切片outputObject的值拷贝,而非指针。函数内部对拷贝切片的修改只会作用于拷贝本身,无法同步到外部的原切片。即便GORM的Find方法接收指针,你传入的&outputObject是拷贝切片的指针,修改的只是拷贝切片的底层数组,原切片的长度、容量不会被更新,所以外部打印时仍为空。
修复方案
方案1:传递切片指针到函数
修改函数参数,让outputObject接收切片指针,直接操作原切片的引用:
// 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)) }
调用时传入切片指针:
var outputObject []Models.Product conditions := map[string]interface{}{"name": "Sample Product"} DB.QueryAllRecords(db, &outputObject, conditions) // 传递&outputObject fmt.Println(outputObject)
方案2:让函数返回查询结果切片
直接让函数返回查询后的切片,外部接收返回值即可:
func QueryAllRecords(db *gorm.DB, conditions map[string]interface{}) ([]Models.Product, error) { var outputObject []Models.Product result := db.Where(conditions).Find(&outputObject) if result.Error != nil { return nil, result.Error } log.Println(Utils.CreateLogMessage("Queried all records", outputObject)) return outputObject, nil }
调用代码调整为:
conditions := map[string]interface{}{"name": "Sample Product"} outputObject, err := DB.QueryAllRecords(db, conditions) if err != nil { // 此处处理错误 } fmt.Println(outputObject)
内容的提问来源于stack exchange,提问作者nikhil0929
相关产品推荐
相关产品推荐

