gpt4 book ai didi

戈朗/戈尔姆 : api end point returning only last record

转载 作者:IT王子 更新时间:2023-10-29 01:51:47 26 4
gpt4 key购买 nike

您好,我现在正在学习使用 golang,并且有一个 api 端点,我想返回数据库中的所有现有用户,但是我的查询只返回最后一个用户。

base.go < responsible for establishing db conns
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite")
var db *gorm.DB //database
func GetDB() *gorm.DB {
return db
}

models.go < responsible for data abstractions

type Account struct {
gorm.Model
Email string `json:"email"`
Password string `json:"password"`
Token string `json:"token";sql:"-"`
}
func GetAllUsers() *Account {

acc := &Account{}
rows, err := GetDB().Raw("select * from accounts").Rows()
if err != nil {
fmt.Print("error")
}
for rows.Next() {
GetDB().ScanRows(rows, &acc)
}
return acc

最佳答案

您在每次迭代中填充相同的 acc 结构。您还传递了一个指向 Account 的指针。尝试添加一个 slice 来保存所有帐户。

func GetAllUsers() []*Account {
accs := []*Account{}
rows, err := GetDB().Raw("select * from accounts").Rows()
if err != nil {
fmt.Printf("error: %v", err)
}
for rows.Next() {
acc := &Account{}
GetDB().ScanRows(rows, acc)
accs = append(accs, acc)
}
return accs
}

关于戈朗/戈尔姆 : api end point returning only last record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com