How can I query all rows out of my table with GORM?

huangapple go评论62阅读模式
英文:

How can I query all rows out of my table with GORM?

问题

这是我的用户表:

id name pass
1 Test 0a2f60e41b1d3d302c0af17bc65d4f48
2 SecUsr 40597ff5ca18da3a91e0ee330496bc77

我该如何使用 GORM 获取所有行?如果我使用 db.Find() 方法,我只能得到第一行。

英文:

This is my users table:

id name pass
1 Test 0a2f60e41b1d3d302c0af17bc65d4f48
2 SecUsr 40597ff5ca18da3a91e0ee330496bc77

How can I get all rows with GORM? If I use db.Find() method, I'll get only the first row.

答案1

得分: 5

使用以下方式使用find函数:

var users []User
// 获取所有记录
result := db.Find(&users)
// SELECT * FROM users;
result.RowsAffected // 返回找到的记录数,等于`len(users)`
result.Error        // 返回错误

请注意,这是Go语言的代码示例,其中User是一个自定义类型。你需要根据你的实际情况进行适当的修改。

英文:

Use the find function in the following way

   var users []User
   // Get all records
   result := db.Find(&users)
   // SELECT * FROM users;
   result.RowsAffected // returns found records count, equals `len(users)`
   result.Error        // returns error 

huangapple
  • 本文由 发表于 2021年10月22日 06:25:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69669422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定