douzhi4991 2019-04-14 02:07
浏览 431
已采纳

golang / gorm:api端点仅返回最后一条记录

Hi I am learning to use golang right now, and there is an api end point, where I want to return all the existing users in the database, however my query is returning only last user.

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

}

  • 写回答

2条回答 默认 最新

  • douqiang1851 2019-04-14 03:09
    关注

    You are filling the same acc struct through each iteration. You are also passing a pointer to a pointer of Account. Try adding a slice to hold all the accounts.

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器