在Gorm的AfterFind()钩子中获取smart-select结构的值。

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

Get smart-select struct's value inside Gorm's AfterFind() hook

问题

我有这个模型:

  1. type User struct {
  2. ID uint
  3. Name string
  4. Age int
  5. Gender string
  6. // 其他字段
  7. }

还有这个钩子:

  1. func (m *User) AfterFind(tx *gorm.DB) (err error) {
  2. // 我不知道如何在这里获取 APIUser 结构体的 Gender 值
  3. return
  4. }

以及这个智能选择结构体:

  1. type APIUser struct {
  2. ID uint
  3. Gender string
  4. }

然后我运行这个查询:

  1. DB.Model(&User{}).Find(&APIUser{}, id)

在 AfterFind() 钩子中,我想在将数据发送给客户端之前对从数据库检索到的数据进行操作,但是我无法在这个钩子中获取值。如何做到这一点?

英文:

I have this model:

  1. type User struct {
  2. ID uint
  3. Name string
  4. Age int
  5. Gender string
  6. // hundreds of fields
  7. }

with this hook:

  1. func (m *User) AfterFind(tx *gorm.DB) (err error) {
  2. // I don't know how to get Gender value of APIUser struct from here
  3. return
  4. }

And this smart select struct:

  1. type APIUser struct {
  2. ID uint
  3. Gender string
  4. }

then I run this query:

  1. DB.Model(&User{}).Find(&APIUser{}, id)

Inside AfterFind() hook I want to manipulate retrieved data from database before send them to client, but I couldn't get the value inside this hook. How to do that?

答案1

得分: 1

AfterFind 应该设置为 APIUserUser

以下是示例代码:

  1. type User struct {
  2. Id uint64
  3. Avatar string
  4. Nickname string
  5. Password string
  6. }
  7. func (user *User) AfterFind(*gorm.DB) error {
  8. return nil
  9. }
  10. type UserSimple struct {
  11. Id uint64
  12. Avatar string
  13. }
  14. func (v *UserSimple) AfterFind(*gorm.DB) error {
  15. v.Avatar = "prefix/" + v.Avatar
  16. return nil
  17. }
  18. us := &UserSimple{}
  19. db.Model(&User{}).Where("id = ?", 123).Find(us)

输出结果:

  1. {123 prefix/avatar}
英文:

The AfterFind should be set to both APIUser and User

Here are sample codes

  1. type User struct {
  2. Id uint64
  3. Avatar string
  4. Nickname string
  5. Password string
  6. }
  7. func (user *User) AfterFind(*gorm.DB) error {
  8. return nil
  9. }
  10. type UserSimple struct {
  11. Id uint64
  12. Avatar string
  13. }
  14. func (v *UserSimple) AfterFind(*gorm.DB) error {
  15. v.Avatar = "prefix/" + v.Avatar
  16. return nil
  17. }
  18. us := &UserSimple{}
  19. db.Model(&User{}).Where("id = ?", 123).Find(us)

Output

  1. {123 prefix/avatar}

huangapple
  • 本文由 发表于 2022年10月13日 10:47:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/74049959.html
匿名

发表评论

匿名网友

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

确定