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

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

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

问题

我有这个模型:

type User struct {
     ID     uint
     Name   string
     Age    int
     Gender string
     // 其他字段
}

还有这个钩子:

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

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

type APIUser struct {
  ID     uint
  Gender string
}

然后我运行这个查询:

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

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

英文:

I have this model:

 type User struct {
      ID     uint
      Name   string
      Age    int
      Gender string
      // hundreds of fields
 }

with this hook:

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

And this smart select struct:

type APIUser struct {
  ID   uint
  Gender string
}

then I run this query:

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

以下是示例代码:

type User struct {
	Id       uint64
	Avatar   string
	Nickname string
	Password string
}

func (user *User) AfterFind(*gorm.DB) error {
	return nil
}

type UserSimple struct {
	Id     uint64
	Avatar string
}

func (v *UserSimple) AfterFind(*gorm.DB) error {
	v.Avatar = "prefix/" + v.Avatar
	return nil
}

us := &UserSimple{}
db.Model(&User{}).Where("id = ?", 123).Find(us) 

输出结果:

{123 prefix/avatar}
英文:

The AfterFind should be set to both APIUser and User

Here are sample codes

type User struct {
	Id       uint64
	Avatar   string
	Nickname string
	Password string
}

func (user *User) AfterFind(*gorm.DB) error {
	return nil
}

type UserSimple struct {
	Id     uint64
	Avatar string
}

func (v *UserSimple) AfterFind(*gorm.DB) error {
	v.Avatar = "prefix/" + v.Avatar
	return nil
}

us := &UserSimple{}
db.Model(&User{}).Where("id = ?", 123).Find(us) 

Output

{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:

确定