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

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
    }
    
    点赞 评论
  • douren7921 2019-04-14 04:32

    Without any special need, better to use default gorm approach to retrieve entries for some model:

    func GetAllUsers() []Account {
        var accs []Account
        res := GetDB().Find(&accs)
    
        if res.Error != nil {
            // Query is failed, handle error as you like.
        }
    
        return accs
    }
    
    点赞 评论

相关推荐 更多相似问题