英文:
gorp PreUpdate method update involuntary columns
问题
请看下面的翻译:
type User struct {
Id int64 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
DateCreate int64 `db:"date_create"`
DateUpdate int64 `db:"date_update"`
}
func (u *User) PreInsert(s gorp.SqlExecutor) error {
u.DateCreate = time.Now().UnixNano()
u.DateUpdate = u.DateCreate
return nil
}
func (u *User) PreUpdate(s gorp.SqlExecutor) error {
u.DateUpdate = time.Now().UnixNano()
return nil
}
我执行了INSERT操作。
user := model.User{
Name: "John",
}
err := dbMap.Insert(&user)
INSERT的结果,没有问题。
1,John,1444918337049394761,1444918337049394761
接着,我执行了UPDATE操作。
user := model.User{
Id: 1,
Name: "John",
}
_, err := dbMap.Update(&user)
UPDATE的结果是:
1,John,0,1444918337049394900
DateCreate列已经更新。
当然,我期望的值是:
1,John,1444918337049394761,1444918337049394900
英文:
see below.
type User struct {
Id int64 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
DateCreate int64 `db:"date_create"`
DateUpdate int64 `db:"date_update"`
}
func (u *User) PreInsert(s gorp.SqlExecutor) error {
u.DateCreate = time.Now().UnixNano()
u.DateUpdate = u.DateCreate
return nil
}
func (u *User) PreUpdate(s gorp.SqlExecutor) error {
u.DateUpdate = time.Now().UnixNano()
return nil
}
I executed INSERT.
user := model.User{
Name: "John",
}
err := dbMap.Insert(&user)
Result of INSERT. no problem
1,John,1444918337049394761,1444918337049394761
continue, I executed UPDATE.
user := model.User{
Id: 1,
Name: "John",
}
_, err := dbMap.Update(&user)
Result of UPDATE
1,John,0,1444918337049394900
Column DateCreate updated.
Of course, my expectation values are
1,John,1444918337049394761,1444918337049394900
答案1
得分: 1
这是因为在初始化你的 user
结构体时,你没有明确设置 user.DateCreate
,这实际上将其设置为0。
gorp 无法猜测你要更新哪些字段,所以它会更新所有字段。
要实现你想要的效果,你需要在以下选项之间进行选择:
- 从ORM中获取结构体,并将字段设置为正确的值。这将执行额外的
select
查询。 - 执行自定义查询,失去了ORM的便利性。
- 我猜你可以使用另一个没有这个字段的
struct
类型。这看起来有点混乱,我不建议这样做。
英文:
That's because when initializing your user
struct, you did not explicitely set user.DateCreate
, which effectively sets it to 0.
gorp cannot guess which fields you mean to update or not, so it updates them all.
To do what you want, you have to choose between trade-offs
- Get the struct from the ORM, with the field already set to the good value. That's one additional
select
query that will be executed. - Execute a custom query, losing the convenience of the ORM
- I'm guessing you could have another
struct
type without this field. That seems messy, I do not recommend that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论