gorp的PreUpdate方法更新非自愿列。

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

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 无法猜测你要更新哪些字段,所以它会更新所有字段。

要实现你想要的效果,你需要在以下选项之间进行选择:

  1. 从ORM中获取结构体,并将字段设置为正确的值。这将执行额外的 select 查询。
  2. 执行自定义查询,失去了ORM的便利性。
  3. 我猜你可以使用另一个没有这个字段的 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

  1. 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.
  2. Execute a custom query, losing the convenience of the ORM
  3. I'm guessing you could have another struct type without this field. That seems messy, I do not recommend that.

huangapple
  • 本文由 发表于 2015年10月15日 23:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/33152031.html
匿名

发表评论

匿名网友

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

确定