0

我很难理解如何使用go-pgUpdateNotZero().

例子:

type Player struct {
  ID            int
  CreatedAt     time.Time `pg:"default:now(),notnull"`
  UpdatedAt     time.Time
  AccountID     *int
}

假设我现在有这个播放器:

+----+------------+------------+------------+
| ID | created_at | updated_at | account_id |
+----+------------+------------+------------+
|  1 | 2020-06-16 | NULL       |         12 |
+----+------------+------------+------------+

在我的 GO 代码中,我需要“删除” AccountID,我需要取消它: from 12to NULL

如果我update()这样使用:

...
player.AccountID = nil
_, err := db.Model(player).WherePK().Update()

它给了我错误:

ERROR #23502 null value in column \"created_at\" violates not-null constraint"

如果我UpdateNotZero()这样使用:

...
player.AccountID = nil
_, err := db.Model(player).WherePK().UpdateNotZero()

它根本不更新AccountID

怎么做?


我认为的相关问题:

4

2 回答 2

2

将更新限制为仅您尝试更改的字段:

_, err := db.Model(player).WherePK().Set("account_id = NULL").Update()
于 2020-11-03T10:13:55.883 回答
0

UpdateNotZero() 仅更新具有值的字段。设置 player.AccountID = nil 意味着你的 player.AccountID 没有价值。我最接近的猜测是 go-pg 将 nil 解析为 null,因此它根本不会更新,因为它 go-pg 将字段视为空。

于 2020-10-13T09:57:20.387 回答