dongpo2002
dongpo2002
2019-04-06 17:10
浏览 10

如何确定需要从修改后的结构更新哪些数据库表列?

The problem that I am facing is more of a code design rather than specifically go related. I am building a simple CRUD application and everything seems to go nice and easy except the updating part: I have a struct type as simple as:

type User struct {
   ID string
   Name string
   Password string
}

and an interface for data storage layer:

type Store interface {
    ...
    Update(user *User) error
    ...
}

The problem is that with most database drivers you can't just pass the whole struct instance and hope the their system knows which fields were modified, the whole document/row gets replaced. How should I track which fields were modified (so that I could update them in the storage layer accordingly)? Maybe pass all the fields I would like to modify to the Update function as a map of interface{}?

图片转代码服务由CSDN问答提供 功能建议

我面临的问题更多是代码设计,而不是具体相关。 我正在构建一个简单的CRUD应用程序,除更新部分外,一切似乎都很轻松:我有一个简单的结构类型:

   type用户结构{
 ID字符串
名称字符串
密码字符串
} 
   
 
 

和数据存储层的接口:

  type存储界面{
 ... 
更新(用户*用户)错误
 ... 
} 
 <  / code>  
 
 

问题是,对于大多数数据库驱动程序,您不能仅传递整个struct实例,并希望其系统知道哪些字段被修改,整个文档/行将被替换 。 我应该如何跟踪修改了哪些字段(以便可以在存储层中进行相应的更新)? 也许将我要修改的所有字段作为接口{}传递给Update函数?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dousi1097
    dousi1097 2019-04-06 18:31

    There are plenty of ways to achieve that. For example you can use setters to change the values.So you can keep track of updated fields. like so :

    type User struct {
       ID string
       Name string
       Password string
       updateFields map[string]bool
    }
    
    func (u *User) SetName(name string) {
       u.Name = name
       updateFields["name"] = true
    }
    

    You can use more automated way by reflection.

    点赞 评论

相关推荐